Jquery multiple ajax check for all done? (order is not important)

Is there a neat way to make sure the bunch of ajax callbacks are over? They do not need to be executed in order, I just need all the data.

one idea is that they all increment the counter at completion and check if the counter == countMax is, but that seems ugly. Also have problems with synchronization? (from simultaneous reading / writing to the counter)

+4
source share
4 answers

.ajaxStop() is available for this, it is launched only when the last of the current ajax requests ends. Here is the full description:

Whenever an Ajax request completes, jQuery checks for other outstanding Ajax requests. If none remain, jQuery fires the ajaxStop event. Any and all handlers registered in the .ajaxStop() method are executed at this time.

For example, if you just want to run something, the document is a good place to connect:

 $(document).ajaxStop(function() { //all requests finished!, do something with all your new fancy data }); 

Or you can display a message when this happens, for example:

 $("#ajaxProgressDiv").ajaxStop(function() { //display for 2 seconds then fade out $(this).text("All done!").delay(2000).fadeOut(); }); 
+8
source

You can see the queue plugin.

+1
source
 var msg= $("<div style='height:100px;width:200px; background:#000;color:#fff; line-height:100px;text-align:center;position:fixed;top:50%;left:50%;z-index:1000;margin-left:-100px; margin-top:-50px'>Ajax done! Click Me!</div>") .click(function(){ $(msg).fadeOut(1000,function(){ $(this).remove(); }); }) $(document).ajaxStop(function(){ $('body').append(msg); }) 

the dot attaches the ajaxStop() event to the document for global validation. you can be more specific if you want.

+1
source

Also $ .active will contain the current number of active AJAX requests, for those trying to use it with JSONP requests (for example, I was), you need to enable it with this:

 jQuery.ajaxPrefilter(function( options ) { options.global = true; }); 

Keep in mind that you will need a timeout in the JSONP request to detect failures.

0
source

Source: https://habr.com/ru/post/1299635/


All Articles