Nadeem Khedr
Nadeem Khedr

Reputation: 5313

Ajax, when response has some value i want to treat it as an ajax error

Whats happening is , I am already working on a big application, the way that the team handles the server side errors that they send a Json response with error=true (its still 200 success) (its hard for me to change that to send different status codes), and in the ajax success they call the same function to alert using a dialog with an error message if error=true else execute the normal logic,

what i want is to use a single ajax event to hook in before any success happens and check first if the value has error=true then don't call its success handler and show the dialog

Upvotes: 2

Views: 141

Answers (2)

Daryl Ginn
Daryl Ginn

Reputation: 1424

A function to validate the response:

var hasErrors = function(response) {
  if(response.error) {
    //...
    return true;
  }
};

Then on each success callback, call hasErrors.

$.ajax({
  //...
  success: function(response) {
    if(hasErrors(response)) return;
    //...
  }
})

Upvotes: 1

Curtis
Curtis

Reputation: 103378

You could change the structure of your success and error handlers to run the same code if error=true.

For example you could do:

$.ajax(
   success: function(data){
      if (data.error){
         RunErrorCode();
         return;
      }
      //success code...
   },
   error: function(){
      RunErrorCode();
});

function RunErrorCode(){
   alert("An error has occurred");
}

Upvotes: 3

Related Questions