88

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?

2
  • Simply remove var myjson= Commented Apr 2, 2013 at 13:05
  • 1
    Have a look at How to return the response from an AJAX call from a function? -- at least it should give you the right idea how to solve the problem. The syntax btw is valid, it just does not do what you want it to. Commented Apr 2, 2013 at 13:07

2 Answers 2

76

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;
});
Sign up to request clarification or add additional context in comments.

4 Comments

The problem with this is that var myjson is not available on the very next line due to timing issues.
@JanDvorak Yes, request executes asynchronously, if you need json data to proceed, you should call other code after setting myjson variable. As solution it could be like 'callbackFuncWithData' from Ravi answer OR just call another function.
Once you do that, there's really no reason to keep myjson declared outside. Just pass it to the callback as an argument.
@JanDvorak Sometimes it's required, for example when you using client filtering. It depends on your app logic.
25

$.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 
}

4 Comments

i dont think the first solution will works. .getJSON is asynchronous so you wont be able to reach any outside variable. What you need to do is set async:false in low level ajax
@lngs: No, it will work. The callback function is a closure and has access to all variables defined in higher scopes. You still have to be careful though when to access the variable, i.e. you cannot access it immediately after you made the call to $.getJSON. In that case you really would have to make a synchronous request.
So how could you know when is ajax call finished and how big is response data? You still need to use callback function to do it.
Yes, how can you know when you can access the data?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.