0

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?

tomkis
  • 125
  • 8
  • those are asynchronous calls. They don't return the result of a request. They issue the request and return. When response comes the callback is called with the result. Its up to you to handle the result in a callback. – Vladimir M Dec 01 '16 at 19:14

1 Answers1

0

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

Community
  • 1
  • 1
Yan Mayatskiy
  • 353
  • 3
  • 12
  • I had an idea in my mind that I could call the .getJSON and then keep the value of my variable person to use it outside the .getJSON or even outside the $(document).ready – tomkis Dec 01 '16 at 19:25