How do I match a country from a list I create and then act if it is inside the list? (GeoIP redirect)

405 views Asked by At

Here is the code that I have. This one works but it only checks for one location at a time.

<script>
jQuery.ajax( { 
  url: '//freegeoip.net/json/', 
  type: 'POST', 
  dataType: 'jsonp',
  success: function(location) {
    // If the visitor is browsing from UK.
    if (location.country_code === 'UK') {
    // Redirect him to the UK Store store.
      window.location.href = 'http://www.domain.co.uk';
    }
  }
} );
</script>

Here is what I've tried:

<script>
jQuery.ajax( { 
  url: '//freegeoip.net/json/', 
  type: 'POST', 
  dataType: 'jsonp',
  success: function(location) {
    // If the visitor is browsing from UK, Germany, France, and Sweden.
    if (location.country_code === 'UK || DE || FR || SE') {
    // Redirect him to the UK Store store.
      window.location.href = 'http://www.domain.co.uk';
    }
  }
} );
</script>

But it doesn't work. I'm not terribly experienced with JavaScript so I'm not 100% sure how to go about making this work. I assume I would be able to create a variable (an array, rather) named something along the liens of "countries" and make it equal to those countries like var countries = ["UK", "DE", "FR", "SE"] and then have the script check to see if the person's current location is one of those countries in the array. However, I don't know how to do that.

Help!

1

There are 1 answers

0
baao On BEST ANSWER
location.country_code === 'UK || DE || FR || SE'

Checks for a string 'UK || DE || FR || SE' and will never be true in your case.

This will work:

if (location.country_code == 'UK' || location.country_code == 'DE' || location.country_code == 'FR' || location.country_code == 'SE') {
// more awesome code 
}

Another aproach would be, as you described, making an array and check if the entry exists. This would be like:

DUMMYCODE:

var countrys = ['DE','UK','SE','FR'];
var a = 'DE';
if (a.indexOf(countrys)) {
    alert('It is');
}