The following geo-redirect code works:
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>
<script>
function geoip() {
$.ajax({
type: 'get',
url: 'https://get.geojs.io/v1/ip/country.json',
success: function(data) {
if (data['country'] == "NZ") {
window.location = "https://www.example.com/";
}
}
});
}
geoip();
</script>
Building on this, I now want to check for a cookie, but can't get it to work. Where am I going wrong?
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>
<script>
var cookieSwitch = 'geo-switch';
if(typeof Cookies.get(cookieSwitch) == 'undefined') { // If cookie is not found, then geo-redirect
function geoip() {
$.ajax({
type: 'get',
url: 'https://get.geojs.io/v1/ip/country.json',
success: function(data) {
if (data['country'] == "NZ") {
window.location = "https://www.example.com/";
}
}
});
}
geoip();
});
</script>
CodePudding user response:
This worked!
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>
<script>
if(typeof Cookies.get('geo-switch') == 'undefined') { // If cookie not found, then redirect if applicable
$.ajax({
type: 'get',
url: 'https://get.geojs.io/v1/ip/country.json',
success: function(data) {
if (data['country'] == "NZ") {
window.location = "https://www.example.com/";
}
}
});
}
</script>
Please note, you will need to include the following for this to work:
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>