Tutorial :Javascript DoEvents equivalent?


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.


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.


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);    }  });  


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.


You can use like this:

$(document).ready(function(){      json = $.parseJSON(          $.ajax({url: '/Handlers/SearchData.ashx', async: false}).responseText      )        alert(json == null);  })  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »