Brian Hogg
Brian Hogg

Reputation: 426

Adding a condition for success or error using jQuery ajax + Wordpress

When using the Wordpress "nonce" system to authenticate an AJAX request, a response of "-1" is returned if the authentication fails. Rather than doing something like this in every jQuery.ajax success function:

success: function(msg){
    if (msg == '-1')
        console.debug('error')
    else {
        // ...
    }
}

is it possible to somehow augment jQuery and add a condition for my application that error: rather than success: is fired when the message returned is "-1"? Obviously much cleaner than a bunch of the same if statements.

I realize the normal response is to have the controller return a 4xx header, but would rather not have the Wordpress plugin change the default behaviour of the ajax handler and possibly mess up other Wordpress plugins.

Thanks!

Upvotes: 2

Views: 2011

Answers (1)

John Hartsock
John Hartsock

Reputation: 86872

There is also an error callback

http://api.jquery.com/jQuery.ajax/

Example

$.ajax({
  url: 'http://somewhere.com/index.html'
  success: function(data, textStatus, jqXHR) {
    //do stuff
  },
  error: function(jqXHR, textStatus, errorThrown) {
    //do stuff
  }
});

Upvotes: 1

Related Questions