0

I am using a jsonp ajax request with jQuery to send some data. When this data could not be processed for some reason, I would like to return the result with a http status other than 200. This way I can use my access logs to parse them for statistics.

Unfortunately, I don't get any response when the status code is not 200, although the jQuery callback is in the response body (when I check with firebug). Is there a way to catch the response?

$.ajax({
    type: 'GET',
    url: '{{ sendMsgUrl }}',
    async: false,
    data: { 'form': formData },
    dataType: 'jsonp',
    success: function(json2) {
        if (json2.status == 'ok')
            // do stuff
        else {
            // output error
        };
    },
    error: function(xhr, status, error) {
        // this doesn't work: it never gets here
        alert(xhr.responseText);
        var json2 = eval("("+xhr.responseText+")");
    }
}).fail(function(jqXhr) {
    // never gets here either
    alert('status '+jqXhr.responseJSON);
});
rolandow
  • 1,049
  • 1
  • 15
  • 28

1 Answers1

2

No. JSONP doesn't use XHR. It injects a <script> element into the page.

In theory, you might be able to find an error event handler to that script, but it won't fire for cross-origin requests (and there isn't much point in using JSONP unless you are making a cross-origin request).

You'll never get any details of the HTTP response headers in any event handler when using JSONP.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • That was my conclusion as well. I am indeed doing a cross-origin request. So my solution to bypass this problem is now to return a code 200 when there was an error returned by the server script. When all is ok, it returns 202 (accepted). The jsonp is now functioning normally, and I still can make a difference in my access logs. This may not exactly be the way the http status codes are ment to be, but for my application this works. – rolandow Oct 13 '14 at 07:07