How to set success function for multiple ajax requests?

How can I install ajax successfor all executed requests?

$.ajax({
  success: function(){ clicked = false;}
});

$('.button').click(function(){
   $.post('file.php',{},function(){});
   $.post('file.php',{},function(){});
   $.post('file.php',{},function(){});
});
+3
source share
2 answers

Do you mean executing one method after completing all the queries?

var counter = 0;
var nRequests = 3;

function multiSuccess() {
    // do something    
}

$('.button').click(function(){
   $.post('file.php',{},function(){
       counter++;
       if(counter == nRequests) {
           multiSuccess();
       }
   });
   $.post(...
   $.post(...
});

In addition, you can see ajaxStop:

Whenever an Ajax request completes, jQuery checks to see if there are any other outstanding Ajax requests. If none remain, jQuery fires an ajaxStop event. Any handlers that were registered in .ajaxStop () are executed at this time.

+2
source

You can use ajaxSetup()to specify default options for ajax calls:

$.ajaxSetup({
  success: function(){ clicked = false; }
});
0
source

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


All Articles