Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the JSON response with jQuery.Ajax for a 400 error?

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

My .error callback function on the jQuery.Ajax object is never called, so I'm using .statusCode{400} function. This runs just fine, however none of the arguments contain the response body.

like image 848
Thomas Hunter II Avatar asked Jan 12 '12 21:01

Thomas Hunter II


People also ask

How do I respond to Ajax JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How can Ajax call error be resolved?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.


1 Answers

Some browsers' XHR implementations refuse to provide the response body if the HTTP status is not 2xx. What I've had to resort to in API design where I couldn't control my clients was to do something like always return 200 and indicate success/failure/status in some other way (e.g., as a top-level attribute in the JSON response).

like image 162
Steven Avatar answered Oct 06 '22 02:10

Steven