views:

1400

answers:

3

Here is my shortened code snippet:

$(document).ready(function() {
$.get("/Handlers/SearchData.ashx",
function(data) {
json = $.evalJSON(data);
});

//do some other stuff

//use json data

alert(json == null);

});

Alert says true because evalJson is not done processing JSON data yet (21kb gzipped). I need to wait somehow for it to finish before using that data - exactly what I'd do with DoEvents in a while loop.

+3  A: 

Instead of executing evalJSON yourself, why not let jQuery figure out when it's done:

$.ajax({
  url:"/Handlers/SearchData.ashx",
  type: "get",
  dataType: "json",
  success:function(d) {
    //d now contains a JSON object, not a string.
    alert(d==null);
  }
});
Salty
This doesn't address his question about delaying code execution until after the XHR returns.
Prestaul
It certainly does. The success function is only called after the request and the JSON parsing are successful, and therefore solve both his problems.
Salty
+3  A: 

There is no equivalent to DoEvents, but you can put the code that depends on your JSON data into a function and call it from the AJAX callback. You can also use the $.getJSON method so you don't have to eval the JSON yourself.

$(document).ready(function() {
    $.getJSON("/Handlers/SearchData.ashx",
    function(data) {
        json = data;
        stuffToDoAfterIHaveData();
    });

    //do some other stuff
});

//use json data
function stuffToDoAfterIHaveData() {
    alert(json == null);
}

Alternatively, jQuery offers a way to make AJAX requests synchronous (i.e. they halt code execution until the response comes back). You can use $.ajaxSetup({ async: false }); or you can call the $.ajax method directly and pass async:false in the options object.

Prestaul
This worked. Thanks.
Vnuk
I had no idea about .ajaxSetup. Thanks once more.
Vnuk
A: 

The only thing similar to doEvents in javascript is setTimeout(). the First argument should be a string with the Code you want to execute after the "system events" are done, and the second argument is the number of milisecs to wait... It's complicated but that is the only solution I know.

Arik Segal