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?
Definition and Usage. The ajaxSetup() method sets default values for future AJAX requests.
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.
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) { // ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With