Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajaxTransport ignores data when returning error

Tags:

jquery

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?

like image 483
Martin Hansen Avatar asked Nov 22 '25 11:11

Martin Hansen


1 Answers

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.

like image 114
Martin Hansen Avatar answered Nov 24 '25 06:11

Martin Hansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!