jQuery getJSON save result into variable

JavascriptJqueryJson

Javascript Problem Overview


I use getJSON to request a JSON from my website. It works great, but I need to save the output into another variable, like this:

var myjson= $.getJSON("http://127.0.0.1:8080/horizon-update", function(json) {

                 });

I need to save the result into myjson but it seems this syntax is not correct. Any ideas?

Javascript Solutions


Solution 1 - Javascript

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

Solution 2 - Javascript

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1229351View Question on Stackoverflow
Solution 1 - JavascriptwebdeveloperView Answer on Stackoverflow
Solution 2 - JavascriptRavi GadagView Answer on Stackoverflow