Wait until all Ajax is completed !!!

by Hozefa 8. August 2012 05:12

Problem is I need to wait for all ajax requests to be done before i execute the next line of code. This can be handled in 2 ways

1) Make the Ajax request synchronous

2) Implement of $.when() in jQuery and handle the next lines in callbacks (success/failure)

To make the Ajax call synchronous

jQuery.ajax({ async: false,....});

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){ 
    // the code here will be executed when all four ajax requests resolve. 
    // a1, a2, a3 and a4 are lists of length 3 containing the response text, 
    // status, and jqXHR object for each of the four ajax calls respectively. 
}

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops. 

Tags:

jQuery

Comments (3) -

Melina Malmanger
Melina Malmanger United States
8/13/2012 1:58:07 PM #

Again, invaluable article on a topic i've been trying to figure out...i'm on adsense only, and making very little, will try out the rest. Thanks!

Reply

Akilah Kwan
Akilah Kwan United States
8/14/2012 3:33:23 AM #

It's really a great and useful piece of information. I am happy that you just shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

Reply

math calendar worksheets 4th grade
math calendar worksheets 4th grade United States
8/19/2012 1:43:12 PM #

Actually it has nothing to do with any of these, but thanks for sharing.

Reply

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Me

Skills set includes - ASP.NET, C#, MVC3, JQuery, Javascript, HTML, AJAX and XML also hobbist programmer and geek to try out new innovations in Microsoft world.

Facebook - facebook.com/hozefam

Twitter - twitter.com/hozefam

Mail - hozefam@gmail.com

 

Month List

Page List