rj tubera rj tubera - 2 years ago 91
Javascript Question

Wait till all multiple asynchronous ajax call are completed

Hello I have multiple ajax call, what I wanted to do is to fire all of them asynchronously then wait till all of them are finished before processing the returned data. I tried using $.when but to no avail. Here is my code:

//form_identifier_list is my flag to get the multiple forms in my html page
function test(form_identifier_list){
var deffereds = [];

$.each(form_identifier_list, function(key,value){
var this_form = $(this).parents('.ajaxed_form');
deffereds.push( $.post($(this_form).attr("action"), $(this_form).serializeForm()) );

$.when.apply($, deffereds).done(function(){
//how to output response obj?? i tried console.log(data) to no avail



I also noticed my ajax requests do not have reponse (which i verified on my browser).

Is there a way to make multiple ajax calls fire asynchronously and then wait till all of them are finished then access the data?


Answer Source

In the jquery page on when, there is a section that says:

In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.

Also there is this on the ajax page

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface

So we can just assign the return value of the ajax to a variable and pass those variables into the .when.

To expand slightly on the example given on the .when page and integrate any number of ajax calls, you can do something like this:

var ajaxes = [];
for(var i=0; i<10; i++) {
    ajaxes.push($.ajax('a.php', {data: {t: i}}));
$.when.apply($, ajaxes)
        for(var i=0;i<arguments.length; i++) {
            $('#output').append(arguments[i] + "<br>");

If you have a known number of ajax calls, it gets a little simpler...you can do something more like this:

var a1 = $.ajax(...);
var a2 = $.ajax(...);
var a3 = $.ajax(...);
$.when(a1,a2,a3).done(function(o1, o2, o3) {

The first example is basically doing the same thing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download