U
U
uaf0x2015-11-03 02:59:59
JavaScript
uaf0x, 2015-11-03 02:59:59

How to track the completion of all ajax requests on the page?

Actually, the task is this, you need to run N requests to the server in a cycle, after all requests have been completed, you will need to run 1 more control one. How to track the completion of all ajax requests on the page?

Now my code looks like this:

jQuery('.btn-primary').on('click', function(event) {
    event.preventDefault();
    for (var i = 0; i <= jQuery('#count').val(); i++) 
    {
      var form = jQuery('.form-horizontal').serializeArray();
      jQuery.ajax({
        url: 'myurl',
        type: 'POST',
        data: {form, i},
          success:function(data)
          {
            jQuery('.cool').append(data);
          }			
      });

    }		
  });


I will be very glad and happy with a constructive proposal.

PS
Suggestions ala learn the mat part, you can not write and so in the process :)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2015-11-03
@alexey-m-ukolov

Yes, of course, you can look at the value of the external counter at a certain interval ...
But you can do it right right away :

var form = {foo: 'bar'},
    requests = [],
    index,
    $xhr;

for (var index = 0; index <= 5; index++) {
    $xhr = $.post('myurl', {'form': form, 'index': index});

    $xhr.done(function (data) {
        console.log('request done');
    });

    requests.push($xhr);
}

$.when.apply($, requests).done(function () {
    console.log('all done');
})

PS How can I make a function run only after another one completes?

S
Super User, 2015-11-03
@sergeystepanov1988

Do it with the ajaxStop method :

$( document ).ajaxStop(function() {
     $('.cool').append(data);  
});

I
Ivan, 2015-11-03
@LiguidCool

Well, as an option, make a counter, and add it when calling a request, and subtract it when it ends or an error. At zero, all requests will end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question