How to trigger jquery.ajax() error callback based on server response, not HTTP 500?

The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:

  • HTTP 404/500 or any other HTTP error message has been received
  • data of incorrect type was received (i.e. you have expected JSON, you have received something else).

In your situation the data is correct (it’s a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.

function handleError(xhr, status, error){

    //Handle failure here

 }

$.ajax({

  url: url,
  type: 'GET',
  async: true,
  dataType: 'json',
  data: data,

 success: function(data) {
     if (whatever) {
         handleError(xhr, status, ''); // manually trigger callback
     }
     //Handle server response here

  },

 error: handleError
});

Leave a Comment