Monitoring all AJAX requests made by JQuery?

ajax, javascript, jquery

Solution

Check out jQuery's "ajaxComplete"; it should be exactly what you're looking for:

http://api.jquery.com/ajaxComplete/

Using it, you can register a handler and that handler will get invoked on every ajax call.

$.ajaxComplete(function() {
    alert('it worked');
});

$.get('foo', {foo: bar} ); // "it worked" would get alerted when this completes

To see the response that came back, just use the XHR object that gets provided, like so:

$.ajaxComplete(function(e, xhr) {
    alert('it worked, and the response was:' + xhr.responseHTML);
});

$.get('foo', {foo: bar} );

And to check the URL you can use a third "settings" arg that gets provided:

$.ajaxComplete(function(e, xhr, settings) {
    alert('it worked, and the response was:' + xhr.responseHTML);
    alert('and the original URL was:' + settings.url);
});

$.get('foo', {foo: bar} );

EDIT

As Yusuf K. helpfully pointed out in the comments, if you're using one of the new versions of jQuery such as jQuery 3, things have moved around. `ajaxComplete` is no longer a static method, but is instead an instance method that you call on `document`:

$(document).ajaxComplete(function(e, xhr, settings) { // ...

Problem

Is there a way to monitor all ajax requests that have been made using JQuery on a page, and to have a callback function be called with the result of each request? E.g I make my ajax requests: ``` $.get('foo', {foo: bar} ); $.get('bar', {bar: foo} ); ``` And then I have a function called each time any of those ajax requests is completed, with the url that was referenced, and the result of the request?

Original source