The setup
In a web application I 'm maintaining there are lots of AJAX calls to submit forms that go like this:
jQuery.post($form.attr("action"), $form.serialize())
.always(commonProcessing)
.done(function() {
// the post succeeded, do something specific (e.g. close a dialog)
});
The commonProcessing function looks for "well known" parts in the JSON response and takes appropriate action (the response may also include request-specific information). It reads something like this:
function commonProcessing(result, outcome) {
switch (outcome) {
case "success":
if (result.notify) {
// show a growl-style notification
}
else if (...) ;
break;
case "error":
// show a generic "unexpected error" notification
break;
}
}
The problem
In many cases I 'd prefer to return an HTTP error code -- say 400 for a submitted form that has invalid data -- because, in addition to this being the natural order of things, it allows me to conveniently put the "successful request" code in a .done handler (if a 200 OK were returned instead then the content would be always parsed, but the .done handler would need to try and find out if this is an "error" or a "really OK" response). At the same time I want to respond to the request with specific information when an error occurs (for example the notify object can contain an error message that explains exactly what was wrong with the request).
The problem is that when an HTTP error code is returned, jQuery does not attempt to parse the response content, in which case the result argument is a jqXHR object instead of the typical parsed JSON.
Is there an elegant way of saying "I know that there was an error, but I also want you to parse the response content"? I could of course do $.parseJSON(result.responseText) since we 're talking about JSON, but that feels clumsy because it sidesteps all the nice jQuery code that sniffs the content type and does the parsing.
5xx?