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