tomkis tomkis - 3 days ago 4
Javascript Question

Can't get the right return value from my API call

I am using http://ip-api.com/json API and I am trying to get an object that would hold the city and and the country of a person.
This is my code.

$(document).ready(function() {

var locationAPI = "http://ip-api.com/json";
var K, C, F;


var Person = {
city: function() {
$.getJSON(locationAPI, function(data) {
return data.city;
});
},
country: function() {
$.getJSON(locationAPI, function(data) {
return data.countryCode;
});
}
};

var x = Person.city;
console.log(x); });


This is the output:

function () {
$.getJSON(locationAPI, function(data) {
return data.city;
});
}


I want it to output a value for ex. - Person.country = USA
What am I doing wrong?

Answer

Your problem is you think .getJSON is a simple function but its not, its a promise function, you have 2 ways to get the data, or in a callback function like this:

$(document).ready(function() {

var locationAPI = "http://ip-api.com/json";
var K, C, F;
var Person;

$.getJSON(locationAPI, function(data) {
  Person = {
    city: data.city,
    country: data.country
  };

  var x = Person.city;
  console.log(x); });

});

or what you can also do is in a promise like this:

var theCall = $.getJSON(locationAPI);

theCall.done(function(data) {...})

you can user .ajax() method and set async: false, this will make the code to wait for the ajax to finish and only then continue (continue only after you set your variable)

BUT this is not the good way to do so, as it blocks the browser to wait for the call, and it might take few seconds for this to finish!!!

$.ajax({
  url: myUrl,
  dataType: 'json',
  async: false,
  success: function(data) {
    //stuff
    //...
  }
});

you can learn more from the docs of ajax, or from this Is it possible to set async:false to $.getJSON call

Comments