I'd like to set global handlers for ajax requests, but only for POST
cases.
Unfortunately, global handlers $.ajaxStart()
and $.ajaxStop()
will fire for all requests and as far as I can see there is no parameter passed onto the handler function. The documentation is also scarce, as most jQuery documentation is.
Can I detect the request type from within a global ajax handler?
I'd like to set global handlers for ajax requests, but only for POST
cases.
Unfortunately, global handlers $.ajaxStart()
and $.ajaxStop()
will fire for all requests and as far as I can see there is no parameter passed onto the handler function. The documentation is also scarce, as most jQuery documentation is.
Can I detect the request type from within a global ajax handler?
Share Improve this question asked Jun 7, 2013 at 9:35 GeorgeGeorge 4793 silver badges19 bronze badges 1- i don´t think so. although ajaxStop is called if EVERY ajax call has finished, therefore what should the request type be if there were more than one request. – luk2302 Commented Jun 7, 2013 at 9:42
2 Answers
Reset to default 5You have to use these events instead: ajaxSend() ajaxComplete()
$(document).ajaxSend(function (event, xhr, options) {
if (options.type.toUpperCase() === "POST") console.log('POST request');;
}).ajaxComplete(function (event, xhr, options) {
if (options.type.toUpperCase() === "POST") console.log('POST request');
});
Using ajaxSend, you can still abort request using: xhr.abort()
EDIT:
Better would be to use jQuery.ajaxPrefilter as in @DemoUser's answer
i guess you could do something like this:
jQuery.ajaxPrefilter(function( options) {
if(options.type !== 'POST') {
options.global = false;
}
});
See:: jQuery prefilters