Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global event handler for AJAX POST requests in jQuery

Tags:

I want to register an event handler for all POST requests done by jQuery.post(...).

I can install a global Handler for all ajax requests with:

$( document ).ajaxComplete(function(ev,xhr) {
  console.log(xhr);
});

But I want to have the handler called only for POST requests. But I can't figure it out:

$( document ).ajaxComplete(function(ev,xhr) {
  if(xhr.__IS_POST_OR_WHATEVER()) {
     console.log(xhr);
  }
});
like image 328
powerpete Avatar asked Feb 27 '19 14:02

powerpete


People also ask

What is global event in AJAX?

Category: Global Ajax Event HandlersThese methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery. ajaxSetup() is true , which it is by default.

What is the name of the jQuery event handler that can be used to get information about an AJAX error?

ajaxError( handler )Returns: jQuery. Description: Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.

How check AJAX call is completed in jQuery?

jQuery ajaxStop() Method The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.


1 Answers

There's one additional argument passed to the ajaxComplete event handler; an object which contains the settings the request was made with. This object has a type property which is what you need to check:

$(document).ajaxComplete(function(ev, xhr, settings) {
  if (settings.type === 'POST') {
    console.log('Do something');
  }
});

More info available in the docs.

like image 181
Rory McCrossan Avatar answered Oct 31 '22 14:10

Rory McCrossan