Why

The article can be: “Do it server-side.“. But sometimes it’s not possible, so, how we can do it?

 

If you need something accurate and you cannot use server-side solutions, you can use libraries like GeoIP or of course Yahoo!/Google APIs.

Let’s see two simple approaches using two different services, we just use JQuery for simplicity’s sake:

IPInfo.io

Having an element made like the following:

You will of course need an element with the id country, such as:

<p>The user with IP <span id="ip"> </span> is located at <span id="city"> </span>, <span id="country"> </span>.</p>

And a very simple JS code like the following:

$.get("http://ipinfo.io", function(response) {
  $("#ip").text(response.ip);
  $("#city").text(response.city);
  $("#country").text(response.country);
}, "jsonp");

NinjaLoader

That’s good if you just need to fetch the country code, such as if you are checking if a user comes from a specific country.

  $.get('http://api.ninjaloader.com/api/getcc',
             function(data) {
               $("#country").text(data);
             }
       });

You will of course need an element with the id country, such as:

<p>The code of your country is <span id="country"> </span>.</p>