0

I have an app where I click a button and the app 15 AJAX POST requests (all asynchronously).

I want to refresh after ALL post requests are done. Is there a way I can detect/confirm that all AJAX requests are complete THEN have the page refresh?

After some research, I found potential one way is to place the .ajaxStop method in one of the ajax success conditions:

success: function(data, status) {       

    $(document).ajaxStop(function() {location.reload(true); });

},

Can someone confirm if this is accurate?

Thanks in advance!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200
  • But what if that choosen ajax with the `.ajaxStop` does not success but fails? Are you talking about [this](http://stackoverflow.com/questions/287188/how-to-know-when-all-ajax-calls-are-complete)? The "easy way"? I do not think that it is meant to be placed within a `success` but simply within the `$(document).ready()`. It will be called once there are no more open ajax-calls (untested). – WcPc Mar 05 '16 at 00:02

1 Answers1

0

Based on my comment:

$(function() {

  $(document).ajaxStop(function() {
    if(foo_flag) {
      foo_flag = false;
      alert('done');
      location.reload(true);
    }
  });

  var foo_flag = false;

  $('.not-foo').click(function() {
    $.ajax({
        method: 'post',
        data: {
          html: 'wololo'
        },
        url: '/echo/html/',
        success: function(result) {
          $("#output").append(result);
        }
      });
  });

  $('.foo').click(function() {
    foo_flag = true;
    for(i = 0; i < 16; i++) {
      $.ajax({
        method: 'post',
        data: {
          html: 'bar',
        },
        url: '/echo/html/',
        success: function(result) {
          $("#output").append(result);
        }
      });
    }
  });
});

This way your reload will not launch whenever any ajax request is done but only after you press your button AND all the ajax-calls are done.

jsfiddle

WcPc
  • 457
  • 2
  • 11