Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set $.ajaxStart() and $.ajaxStop() to fire only on POST requests?

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?

like image 291
George Avatar asked Jun 07 '13 09:06

George


2 Answers

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

like image 79
A. Wolff Avatar answered Oct 22 '22 03:10

A. Wolff


i guess you could do something like this:

jQuery.ajaxPrefilter(function( options) {
    if(options.type !== 'POST') {
        options.global = false;
    }
});

See:: jQuery prefilters

like image 27
Sudhir Bastakoti Avatar answered Oct 22 '22 03:10

Sudhir Bastakoti