This might sound like another of those questions with “best way” or “best practice” but I couldn’t find anything related that could give me some light.
The scenario… I have some ajax calls. Everything works alright. I make the calls, get the results back, change fields, values, colours. Nothing interesting here.
But then, yesterday, I was writing another ajax method. Basically, two date fields to return number of days without holiday days. Again, nothing interesting here… until the point where I could pass invalid dates.
Now, my question… in an ajax interaction, whenever I have a scenario where the data passed by an ajax call is invalid (understand invalid, the formatting is wrong or the data does not suit some sort of business), should I respond any ajax call that contains data not suitable for my server side processes with a http status different of 200 or create a model with errors and messages and everything?
I’ve found people doing like AjaxRespond models and responding that. My point here is that if the data is not good, I could respond a http status 200 and deal with the ajax model to check if there are errors or not but I could also respond a 500 and be sure that there is an error.
I can see two perspectives here.
1- the call was successful from javascript/ajax side and therefore 200 is the logical way to respond. This one sounds like “I have good news and bad news”.
2- the call was successful but the data was busted and therefore 500 (or any other suitable status) was returned. This one is more doing business logic inside try/catches.
This is a good place to use deferreds. Here is jQuery’s implementation, but you don’t have to use jQuery. In a nutshell, you have all your ajax calls return a promise that any callbacks bind to. When the response comes back from the server, you evaluate it via a middleware method (then
in jQuery’s implementation) and resolve or reject the promise depending on the status. That way, callbacks are triggered or not depending on the status, not on whether the ajax request itself succeeded or failed. You can also use this middleware approach to instantiate or populate an error model…
Note: Do not change your HTTP response code at the headers level! Send status along with the data so that you truly know whether the server handled the request predictably or not.
3