powerpete
powerpete

Reputation: 3052

Global event handler for AJAX POST requests in jQuery

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);
  }
});

Upvotes: 6

Views: 791

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 4

Related Questions