Skip to content Skip to sidebar Skip to footer

Monitoring All Ajax Requests Made By Jquery?

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 aja

Solution 1:

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) { // ...

Solution 2:

Example of accessing url for any request using ajaxComplete... taken straight from docs:

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

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxComplete handler. The result is ' +
                     xhr.responseHTML);
  }
});

If you console.log() xhr and settings objects to your browser console you can see all the data you have access to within ajaxComplete

Solution 3:

You can store the requests in an array and use the chained callbacks if that's what you mean:

functioncallback( data ) {
  // do something with the request
}

var requests = [];
requests.push( $.get('foo', { foo: bar }) ); // add to array and run request
requests.push( $.get('bar', { bar: foo }) );

requests.forEach(function( request ) {
  request.done(function( data ) {
    callback( data );
  });
});

Post a Comment for "Monitoring All Ajax Requests Made By Jquery?"