//We're going to create a new deferred with pipe, then register our callbacks on // that new deferred. var myXhrDeferred = $.post('/echo/json/', {json:JSON.stringify({'error':true})}) .pipe( //done filter function (response) { if (response.error) { //If our response indicates an error //we'll return a rejected deferred with the response data return $.Deferred().reject(response); } return response; }, //fail filter function () { //If the request failed (failing http status code) //we'll call this an error too — we pass back a //deferred that's rejected here as well. return $.Deferred().reject({error:true}); } ); //Now our done and fail callbacks will run based on whether the JSON response returns error:true myXhrDeferred .done(function (response) { $("#status").html("Success!"); }) .fail(function (response) { $("#status").html("An error occurred"); });
<div id="status"></div>