crunchy crunchy - 2 months ago 4
Ajax Question

jQuery - completion of multiple ajax-requests

in a

$.each()
I do a AJAX-request:

$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
}
});
});


now I would like to show a message if every AJAX-request in the
$.each()
is complete. But how can I do this, As AJAX is asynchronous?

Answer

With simple javascript you can do it in following way:

var counter = 0;
$.each(all, function(i,v) {                                 
    $.ajax({
        url: "/mycontroller/"+encodeURIComponent(v),
        success: function(data){ 
            $('#inner').append(data);
            counter++; //increment the counter
        },
        error: function(){
            counter++; //increment the counter
        },
        complete : function(){
            //check whether all requests been processed or not
            if(counter == all.length)
            {
                alert("All request processed");
            }
        }
    }); 

});
Comments