开发者

What response/status code should I send to an AJAX request when there is a user/form validation error?

I am creating a feature of开发者_如何学C my web application where a user can "edit-in-place" a record and submit the form via AJAX using jQuery.

When someone is "ajax editing" a record and they submit the form with valid data, I send a 200 status code, which triggers the jQuery AJAX Success function, then ignore the response body (since it was successful, I don't need it), and collapse the form.

When there are form validation errors, I send a 400 status code in order to trigger the jQuery error method, and in the body of the request I specify which fields did not validate.

In a previous StackOverflow question, someone mentioned that it "seemed odd" that I was sending a 400 status code and working with the response body. Is my approach not a best-practice? What would you recommend that I do in this situation?


For me, HTTP status codes are for signalling at the HTTP layer, not the application layer. I would say the appropriate response to bad data properly submitted (if you see what I mean) is a 200 with an application-layer error code. I use JSON for this. My requests always get back a small JSON message, which always has a flag indicating success/failure at the application level. My wrappers for ajax calls know about this and dispatch as appropriate.


Using the payload of a 4xx status code is just fine. There's nothing in the HTTP spec saying otherwise.

If you want something more specific than 400, have a look at 422 Unprocessable Entity.


I would return 200 with an (application) error page, or the original page with an error option, which triggers an informational panel with the error description.

The reason for this is that the HTTP error codes are for the browser's response to the web server, not for your web application. Keep your application logic separate from what happens when the browser and server talk to each other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜