How to access JSON response using jQuery.Ajax for error 400?

In jQuery, I submit forms to the server. When there is a validation error, I get a 400 error from the server, and the document body is valid JSON. I would like to know how to access the data returned from the server.

The myerror callback function in the jQuery.Ajax object is never called, so I use the .statusCode {400} function. This works fine, however, none of the arguments contains the body of the response.

+8
javascript jquery
source share
5 answers

Some versions of XHR browsers refuse to provide a response body if the HTTP status is not 2xx. What I had to resort to developing an API where I could not control my clients was to do something like return 200 and indicate success / failure / status in some other way (for example, as a top-level attribute in JSON response).

+7
source share

I am trying to get json response with status 400 and it works on IE7.8 and 9, Firefox and Chrome (Safari not tested).

... error: function(xhr) { error(xhr.responseText); } ... 
+5
source share

I had no problems using statusCode in the callback. However, statusCode as a callback function does not matter .

jQuery.Ajax

I think you should try a different approach to how to handle verification errors on the server side, return a status code of 200, but with the parameter "error_count" and from there.

can you post the part of the code you use (total $ .ajax you use ...)?

+1
source share

For me (Chrome), the responseText property of the xhr response contains only "BAD REQUEST" when the statusCode is 400. Thanks Stephen for your answer; I struggled with this since in Postman I could get the json data that I returned from my REST controller, but could not find it in the jQuery Ajax answer.

0
source share

"If json is specified, the response is parsed using jQuery.parseJSON and then passed as an object to the success handler. The processed JSON object is made available through the responseJSON property of the jqXHR object. "

http://api.jquery.com/jquery.ajax/

If you specify your callback using statusCode as indicated in the question:

"If the request is successful, the status code functions take the same parameters as the success callback; if this leads to an error (including 3xx redirection), they accept the same parameters as the error callback. " (JqXHR, textStatus, errorThrown )

0
source share

All Articles