Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call alert after all ajax requests are done?

I'm making in code a few requests with JQuery and get. It looks like:

$.get('address1', function() { ... });
$.get('address2', function() { ... });
$.get('address3', function() { ... });

// This code should be runned when all 3 requests are finished
alert('Finished');

So, are there any ways to detect whether there is still processing request and run marked code only when all 3 requests are finished.

Thanks.

like image 277
Max Frai Avatar asked Jul 16 '11 12:07

Max Frai


1 Answers

You can make use of deferred objects [docs] introduced in jQuery 1.5:

$.when(
    $.get('address1', function() { ... }),
    $.get('address2', function() { ... }),
    $.get('address3', function() { ... })
).then(function() {
    alert('Finished');
});

Reference: jQuery.when

The jQuery learning center has a nice introduction to deferred objects / promises.

like image 122
Felix Kling Avatar answered Sep 27 '22 21:09

Felix Kling