jquerygetjson

jQuery getJSON return data


I want return data from the jQuery getJSON method out of a function.

console.log(loadJson());

I think the failure is that I used a function in a function and my return is in the inner function. I have tried several opportunities and I can't find the correct solutions.

The result is always "undefined".

This is my simple code:

function loadJson(){
  $.getJSON('data.json', function (data) { 
    return data;
   });
}

console.log(loadJson());

Thanks for help.


Solution

  • The getJSON function from jQuery is asynchronous. It has no return value until data is returned by the server.

    Solution would be to use callbacks to handle asynchronous results or Promises with async or await.

    Using callback:

    function loadJson(callback) {
        $.getJSON('data.json', function(data) { 
            callback(data);
        });
    }
    
    loadJson(function(data) {
        console.log(data);
    });
    

    Hope this helps you.