JQuery post fail callback does not display response for code 400

I have the following jQuery submit request:

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

In my ajax.php file, when something goes wrong, I return an HTTP 400 response code with the message:

 header("HTTP/1.0 400 Error"); echo "Some error message"; exit(); 

When I check the response to an error call in my browser, I can see the Status Code:400 Bad Request status code and the response text that I sent in the error message. But jQuery .fail does not display my response .

How can I access the text of the error / error response?

EDIT

I tested my code and the .fail callback .fail , I just can't get the displayed response message.

+6
source share
2 answers

You need to use jqXHR :

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

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

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

You can use the responseText property to get an error message like:

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

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

+8
source

I always use 500 for code with ajax error, and .fail usually takes me. The JQ API for .post has a long list of nested links describing how they handle the JqXHR object and how it interacts with JQ in general.

Since you are not running .fail with your status, you can check your success with your status code in the .success or .done function.

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

The advantage of doing your own checks in .done or .success is that you can define some elegant behaviors for different statuses that you want to return from your server. There are literally dozens of different ways to handle ajax returns and determine callback behavior.

** Here is another question that has some other solutions.

JQuery AJAX error handling (HTTP status codes)

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

0
source

All Articles