0

I'm using $get.JSON() and ipinfo.io to retrieve the users country of origin, but somehow I'm not able to store this into a variable. When I try in the following way, the variable contains an object.

var loc = $.getJSON("http://ipinfo.io/?callback=?", function(response) {
    return response.country;
});
console.log(loc);

This logs a somewhat nonsensical object, looping over the contents of the object doesn't result in anything meaningful (to me anyway).

The following:

$.getJSON("http://ipinfo.io/?callback=?", function(response) {
     console.log(respose.country);
     window.locationGlobal = respose.country;
});
console.log(locationGlobal)

results in one correct log, the first one, and a reference error on locationGlobal (is not defined). Which I find baffling because when I call the variable in the JS console I get the expected result.

Is there anyone who can enlighten me? I am in (dire) need of enlightenment here. There has to be something that I'm overlooking but I'm not able to see it. Thanks!

update: So I guess I was trying to assign the result of the callback to a global before it was retrieved. If I called the global after the page was loaded with a button on the page the correct answer was retrieved. I wanted to change text on the page depending on the location of the visitor. I was only was taking two location in consideration. My solution could use some refactoring (on multiple fronts) but at the moment I have something of a "If it aint broken don't try an fix it" attitude...link

AndrewRMillar
  • 608
  • 1
  • 7
  • 17

0 Answers0