Proper status codes for JSON responses to Ajax calls?

Posted by anonymous coward on Stack Overflow See other posts from Stack Overflow or by anonymous coward
Published on 2011-02-16T19:52:02Z Indexed on 2011/02/16 23:25 UTC
Read the original article Hit count: 228

Filed under:
|
|
|
|

My project is returning JSON to Ajax calls from the browser. I'm wondering what the proper status code is for sending back with responses to invalid (but successfully handled) data submissions.

For example, jQuery has the following two particular callbacks when making Ajax requests:

success: Fired when a 200/2xx status code is delivered along with the response.

error: Fired when 4xx, 5xx, etc, status codes come back with the response.

If a user attempts to create a new "Person" object, I send back a JSON representation of the newly created object upon success, thus giving javascript access to the necessary unique ID's for the new object, etc. This, of course, is sent with a 200 status code.

If a user submits malformed or invalid data (say, an invalid/incomplete "name" field), I would like to send back the validation error messages via JSON. (I don't see why this would be a bad thing).

My question is: in doing so, should I send a 200 status code, because I successfully handled their invalid data? Therefore, I'd be using the jQuery success callback, but simply check for errors...

Or, should I use a 4xx status code, perhaps 'Bad Request', because the data they sent me is invalid? (and thus, use the error callback to do the necessary client-side notifications).

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about AJAX