Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 961
Ali Avatar asked Dec 24 '12 21:12

Ali


People also ask

What is ajaxSetup?

Definition and Usage. The ajaxSetup() method sets default values for future AJAX requests.

Are AJAX requests secure?

Since AJAX calls are encrypted with a session key, AJAX queries cannot be sent directly to the server. If an attempt is made to send queries directly, the response given by the page will be "Forbidden," as the page expects to receive encrypted text in the AJAX call.


1 Answers

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) { // ...
like image 101
machineghost Avatar answered Oct 12 '22 04:10

machineghost