1

How do I get country code using javascript only, I am not allowed to use jQuery.

I have seen some sites like http://ipinfo.io , but all examples uses JQuery getJson, can I implement the same method :

var country_code = null;
$.getJSON('http://ipinfo.io/' + userip, function(data){
    country_code = data.country;
    alert(country_code);
});

I tried the following, but it returns a page instead:

var request = new XMLHttpRequest();

request.onload = function(elements) { console.log(elements); };
request.open("get", "http://ipinfo.io", true);
request.send();
jeffdill2
  • 3,968
  • 2
  • 30
  • 47
Bilal Halayqa
  • 932
  • 1
  • 6
  • 25

1 Answers1

2

Working example:

var someIp = '8.8.8.8';
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == XMLHttpRequest.DONE) {
    if (xmlhttp.status == 200) {
      document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
    else if (xmlhttp.status == 400) {
      alert('There was an error 400');
    }
    else {
      alert('something else other than 200 was returned');
    }
  }
};

xmlhttp.open("GET", "//ipinfo.io/"+someIp+"/json", true);
xmlhttp.send();
<div id="myDiv">
  pending
</div>

The ipinfo.io service returns JSON format only when proper header requesting JSON is attached. But it can be specified easily also with the /json directly in the requesting url.

Filip Matthew
  • 318
  • 2
  • 8