jQuery post fail callback does not display response for code 400 jQuery post fail callback does not display response for code 400 ajax ajax

jQuery post fail callback does not display response for code 400


You need to use jqXHR:

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

.fail is one the available Promise methods of the jqXHR object,

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

You can use the responseText property to get the error message as :

$.post("ajax.php", data).done(    function(response){        // do something when response is ok     }   ).fail(    function(jqXHR, textStatus, errorThrown) {          $("#error").html(jqXHR.responseText);     } );

Reference : http://api.jquery.com/jquery.ajax/#jqXHR


I always use 500 for an ajax fail code and it usually gets picked up by .fail for me. JQ API for .post has a long list of nested links describing how they handle JqXHR object and how it interacts with JQ as a whole.

Since you're not triggering .fail with your status, you could have your success check for your specific status code in the .success or .done function like so.

//post stuff.success(function(response){     if(response.status == 400){      //error stuff   }});

The advantage of performing your own checks in .done or .success is that you can define some nifty behaviors for different statuses you'd like to return from your server. There are literally dozens of different ways to handle ajax returns and define callback behaviors.

**Here's another SO question that has some other resolutions.

jQuery AJAX Error Handling (HTTP Status Codes)

**The syntax here is slightly different because this question focused on the .ajax method instead of .post, but the ideas and resolutions proposed should still work.