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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With