Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax custom error handler

I am writing an backbone js web app on top of an JSON server that returns JSON responses in JSend specification format.

Here are a few examples of that format:

GET /posts

{
 "status": "success",
 "data": {
   "posts" [
     {"id": 1, "title": "A blog post"}, 
     {"id": 2, "title": "another blog post"}
   ]
 }
}

POST /posts

{
  "status": "fail",
  "data": {
    "title": "required"
  }
}

By default the "error" event in $.ajax gets triggered by http codes, but since the JSend specification format does not use HTTP codes at all, I have to rewrite the $.ajax error handler.

The way it works by default (http codes):

$.ajax({
  error: function() {
    // Do your job here.
  },
  success: function() {
    // Do your job here.
  }
});

How can I rewrite the $.ajax error handler that it gets triggered when parsed the body and if the "status" property is "fail" or "error"?

like image 821
onlineracoon Avatar asked Nov 20 '25 17:11

onlineracoon


2 Answers

As counter-intuitive as it seems, you will have to put it in the success function. Simply check the value yourself:

$.ajax({
  error: function() {
    // Handle http codes here
  },
  success: function(data) {

    if(data.status == "fail"){
      // Handle failure here
    } else {
      // success, do your thing
    }

  }
});
like image 157
James Montagne Avatar answered Nov 22 '25 05:11

James Montagne


To keep the things DRY you can use something like this:

function JSendHandler(success, fail) {
    if (typeof success !== 'function' || typeof fail !== 'function') {
        throw 'Please, provide valid handlers!';
    }
    this.success = success;
    this.fail = fail;
}

JSendHandler.prototype.getHandler = function () {
    return function (result) {
        if (result.status === 'fail') {
            this.fail.call(this, arguments);
        } else {
            this.success.call(this, arguments);
        }
    }
};

function success() { console.log('Success'); }
function error() { console.log('Fail!'); }

var handler = new JSendHandler(success, error);

$.ajax({
  error: error,
  success: handler.getHandler()
});
like image 43
Minko Gechev Avatar answered Nov 22 '25 05:11

Minko Gechev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!