I have created a jQuery ajaxTransport handler (for some testscases I have) that is supposed to simulate a 403 validation error on the server.
The problem is that when I do this and return a 403 error, the data is not returned, not as json and not as responseText.
Here is my code (simplified): (also on jsfiddle http://jsfiddle.net/znTCL/1/)
$.ajaxTransport('json',function( options, originalOptions, jqXHR ) {
return {
send: function( headers, completeCallback ) {
completeCallback(403, 'Forbidden', {json : {'Title': 'Title is required.'}});
}
};
});
$(function() {
$.ajax({
url :document.location,
type : 'POST',
data : {Title:''},
dataType : 'json'
}).fail(function(){
console.log(arguments);
});
});
If I return a 403 for real on the server and don't use ajaxtransports, then everything works as expected, the fail callback have the jqXHR object that also contains the responseText that I can then parse as JSON and then show validation errors based on that. With ajaxtransports the jqXHR object have no reponseText property.
If I return a 200 in the transport, the data comes along as it should and responseText is as it should.
Am I doing anything wrong or is this a limitation of jQuery ajaxTransports?
It seems you can't return json to the completeCallback when you return an error. Even though your request was a json request.
Returning text works:
completeCallback(403, 'Forbidden', {text : 'Title is required.'});
Or
completeCallback(403, 'Forbidden', {text : JSON.stringify({'Title': 'Title is required.'})});
Now responseText of the jqXHR object in the fail callback is not undefined, it contains the text I supply and I can now parse 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