Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

http

I am creating a feature of 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?

like image 784
Andrew Avatar asked Jul 15 '11 00:07

Andrew


1 Answers

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.

like image 132
T.J. Crowder Avatar answered Oct 22 '22 01:10

T.J. Crowder