3

I'm trying to do some action:

var function some_action() {
    // ...
}

But this action requires all the ajax to be finished, so I wrote this way:

$(document).one('ajaxStop', some_action);

Ok, when all pending ajax request finishes, the function would be fired.

But sometimes when I do it, there is no pending ajax requests, so the one event do not fire in these cases!

So I'm finding a way to check if there is any ajax requests that are in progress?

Like:

if($.hasAjaxRunning()) {
    $(document).one('ajaxStop', some_action);
} else {
    some_action();
}

So that I can make the action guaranteed to be fired.

Alfred Huang
  • 17,654
  • 32
  • 118
  • 189

2 Answers2

5

Simple "IF" Statement

if ($.active == 0) {
   some_action();
}

As a jQuery Function

$.hasAjaxRunning = function() {
   return $.active != 0;
}
xRavisher
  • 838
  • 1
  • 10
  • 18
  • 1
    This is the better solution. More info can be found here: https://stackoverflow.com/q/3148225/1455074 – tschwab May 26 '20 at 15:11
2

We can simply set a global variable to flag that state:

// site.js
$(function() {
    window.ajax_loading = false;
    $.hasAjaxRunning = function() {
        return window.ajax_loading;
    };
    $(document).ajaxStart(function() {
        window.ajax_loading = true;
    });
    $(document).ajaxStop(function() {
        window.ajax_loading = false;
    });
});

Seeing that, if any ajax request starts, the variable window.ajax_loading is set to true. And when all ajax requests was ended, the flag is set to false.

Alfred Huang
  • 17,654
  • 32
  • 118
  • 189