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;
}
}
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.
What about using a try/catch block of code?
try{
var response = $.parseJSON(response) etc
}
catch(error){
console.log(error) //error handling here
}
That is what I use to account for the instances where the response is not in JSON format as expected but an error code of some sort. Apologies in advance if I have misunderstood the question!
I don't think you can modify the jqXHR object to behave like that. Looking through the API (here) the closest thing that occurs to me that might solve your issue is the overrideMimeType()
method. Something like:
beforeSend: function(xhr){
xhr.overrideMimeType("application/json; charset=UTF-8");
}
If you're looking to take control in a more fine-grained manner, why not implement the AJAX call manually and return the object you wish, in the format you need it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With