1

Could anyone explain to me why the following is happening. First of all see my code below. Trying to get data via a JSON request and save it for later use.

        var entities;

        //@jsonGetEntities is an url build by asp.net MVC and this works
        $.getJSON("@jsonGetEntities", function(getdata) {
            entities = getdata;

            //I would expect that this is the first alert
            alert(entities + "first");
        });            

        //I would expect that this is the second alert
        alert(entities + "second");

However, the alert that I would expect to be first comes second and entities is actually filled.

In the last alert entities is not filled.

I can't seem to understand why my json is not saved to the var and why an alert that is called later is executed earlier? Could you also give me a possible other solution?

Nick N.
  • 12,902
  • 7
  • 57
  • 75
  • 2
    Yet another duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin May 22 '13 at 13:07
  • I don't see how this is a duplicate, I don't even use prototype. Thanks for the tip though. The answers there can come in handy. – Nick N. May 22 '13 at 13:12
  • It's Ajax. The problem is the same. The solution is the same. The syntax is very slightly different. – Quentin May 22 '13 at 13:12

2 Answers2

3

That is because getJSON() is asynchronous.

The first alert is inside the success callback of getJSON which gets executed asynchronously once the server returns.

The second alert however, runs immediately after triggering the AJAX request (via getJSON())

techfoobar
  • 65,616
  • 14
  • 114
  • 135
0
 $.getJSON("@jsonGetEntities", function(getdata) {
            entities = getdata;

            //I would expect that this is the first alert
            alert(entities + "first");
            setTimeout(function() {
               //I would expect that this is the second alert
               alert(entities + "second");
            },2000); // wait 2 sec.
        });            
Raf A.
  • 124
  • 1
  • 4
  • 9
  • Why would you wait to execute the second alert? – War10ck May 22 '13 at 13:09
  • And how can you be sure it'll be done in 2000 ms! And why is the second alert inside the callback? The whole point was about how he can use it *outside*.. – techfoobar May 22 '13 at 13:11
  • This answer doesn't make any sense, I am not going to wait for a random number of seconds. That doesn't seem like a clean solution. Thanks though. – Nick N. May 22 '13 at 13:15