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();
8
  • Can you use fetch or do you have to use XHR? Commented Feb 2, 2017 at 19:41
  • have you even googled this? Commented Feb 2, 2017 at 19:41
  • fetch is not supported in IE Commented Feb 2, 2017 at 19:42
  • @cruiser , it is been an hour googling it Commented Feb 2, 2017 at 19:42
  • 1
    See youmightnotneedjquery.com/#json. They have alternatives to JQuery methods written in pure javascript. Commented Feb 2, 2017 at 19:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I just found that I missed to append the IP , check the question. Thanks a lot :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.