Lee Lee - 4 months ago 13
Ajax Question

When all AJAX requests complete

I have an ajax request that grabs some data and then splits it up into an array. The array length is variable.

var ajax1 = $.ajax({
url: 'myurl.php',
type: "GET",
dataType: "jsonp",
success: function (data) {

//create an array

}

});


Once I have the array, I want to loop through it and in each iteration run another AJAX request. I put it inside a $.when to make sure the initial ajax request was complete:

$.when(ajax1).done(
function() {

for (i = 0; i < array.length; ++i) {

$.ajax({
url: 'anotherurl?=' + myarray[i],
type: "GET",
dataType: "jsonp",
success: function (data) {

//do stuff here

}
});

}

}
)


My question is, how can I get a message box to pop up when the for loop has completed all the AJAX requests? A simple
alert('complete')
at the end of the loop won't work as the AJAX is done async.

Answer

You can achieve this by also using $.when. You just need to store all the AJAX requests you make in an array and apply() that array to $.when. Try this:

$.when(ajax1).done(function() {
    var requests = [];
    for (i = 0; i < array.length; ++i) {
        requests.push($.ajax({
            url: 'anotherurl?=' + myarray[i],
            dataType: "JSONP",
            success: function (data) {
                // do stuff here
            }
        }));
    }
    $.when.apply($, requests).done(function() {
        console.log('complete');
    });
})

You can also shorten the logic slightly by using map(), although be aware this won't work in < IE9.

$.when(ajax1).done(function() {
    var requests = array.map(function() {
        return $.ajax({
            url: 'anotherurl?=' + myarray[i],
            dataType: "JSONP",
            success: function (data) {
                // do stuff here
            }
        });
    });
    $.when.apply($, requests).done(function() {
        console.log('complete');
    });
})
Comments