How wait for return value from $.getJson

1.4k Views Asked by At

I want to return a value from a getJson function, but the event does not take place, since getJSON wait. I tried realized callback function but result is same. My code is

function getFBName(callback) {
  $.getJSON("http://ip-api.com/json/?callback=?", function (data) {
    callback(data);
  });
}

function handleName(a) {
  console.log(JSON.stringify(a));
  return JSON.stringify(a);
}

console result is true but returned value is "undefined"

1

There are 1 best solutions below

1
Quethzel Diaz On BEST ANSWER

If you want to get the value to return the function getFBName. You can do somthing like this:

function getFBName(callback) {
    $.getJSON("http://ip-api.com/json/?callback=?")
    .done(function(result) {
        console.log(result.a); //assuming that exist the element a
    });
};

Note: You can put a breakpoint in "console.log" and check why return undefined. Make sure that you access to the result of json response correctly. Remember that getJSON is asynchronous