Sunil Kumar
Sunil Kumar

Reputation: 3242

How to check if any AJAX request is running on page via JQuery?

Is there any way to find any AJAX request is running on page (on $(window).load event) ?

I want to apply some event when all ajax request completed.

I have tried

.ajaxStop(function(){ })

but I want to put this block(ajaxstop) when AJAX request exist on page.

Any help would be appreciated.

Upvotes: 0

Views: 3056

Answers (3)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

You can do something like this, which creates a function that will tell you how many active requests are pending.

const activeAjaxRequests = (function(send) {
    var active_requests = 0;
    XMLHttpRequest.prototype.send = function(body) {
        active_requests++;
        this.addEventListener("readystatechange", function() {
            if(this.readyState === 4) active_requests--;
        });
        send.call(this, body);
    };
    return ()=>active_requests;
})(XMLHttpRequest.prototype.send);

var active_requests = activeAjaxRequests();

console.log(`There are currently ${active_requests} active ajax requests.`);

Upvotes: 1

Ricardo Rocha
Ricardo Rocha

Reputation: 16236

Make sure this functions is the first thing loaded to the browser:

(function(open) {

    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {

        this.addEventListener("readystatechange", function() {
            //Put your code here
        }, false);

        open.call(this, method, url, async, user, pass);
    };

})(XMLHttpRequest.prototype.open);

Each time an ajax response is retrieve, the following listner functions is called, and is in there that you should put your code:

this.addEventListener("readystatechange", function() {
    //Put your code
}, false);

Note: This code was extracted from this answer which was used to intercept all ajax requests and from this answer you don't need to pass the parameters on functions:

(function(open) {
    XMLHttpRequest.prototype.open = function() {
        this.addEventListener("readystatechange", function() {
            // put your code here!
        }, false);
        open.apply(this, arguments);
    };
})(XMLHttpRequest.prototype.open);

Upvotes: 0

Barmar
Barmar

Reputation: 781058

Put this at the beginning:

var ajax_running = false;
$(document).ajaxStart(function() {
  ajax_running = true;
});

Then you can later use:

$(document).ready(function() {
  if (ajax_running) {
    $(document).ajaxStop(function() {
      // do something
    })
    ajax_running = false;
  }
});

Upvotes: 1

Related Questions