JSONP request error handling JSONP request error handling json json

JSONP request error handling


If you check jQuery.ajax() documentation, you can find:

error

A function to be called if the request fails (...) Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.

Because of that, you're forced to find workaround. You can specify timeout to trigger an error callback. It means that within specified time frame the request should be successfully completed. Otherwise, assume it has failed:

$.ajax({    ...    timeout: 5000, // a lot of time for the request to be successfully completed    ...    error: function(x, t, m) {        if(t==="timeout") {            // something went wrong (handle it)        }    }});

Other issues in your code...

While JSONP (look here and here) can be used to overcome origin policy restriction, you can't POST using JSONP (see CORS instead) because it just doesn't work that way - it creates a element to fetch data, which has to be done via GET request. JSONP solution doesn't use XmlHttpRequest object, so it is not an AJAX request in the standard way of understanding, but the content is still accessed dynamically - no difference for the end user.

$.ajax({    url: url,    type: "GET"    dataType: "jsonp",    ...

Second, you provide data incorrectly. You're pushing javascript object (created using object literals) onto the wire instead of its serialized JSON representation. Create JSON string (not manually, use e.g. JSON.stringify converter):

$.ajax({    ...    data: JSON.stringify({u: userid, p: pass}),    ...

Last issue, you've set async to false, while documentation says:

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.


Two ways to handle error,

  1. There is no error handling for cross domain JSONP requests. Use jsonp plug-in available on Github https://github.com/jaubourg/jquery-jsonp that provides support for error handling.

  2. jQuery ajax Timeout - Timeout after a reasonable amount of time to fire the error callback because it might have failed silently. You may not know what the actual error (or error status) was but at least you get to handle the error


I've been struggling like you for a while trying to handle errors on ajax jsonp DataType requests, however I want to share you my code, hope it helps. A basic thing is to include a timeout on the ajax request, otherwise it'll never enter the error: function

$.ajax({url: "google.com/api/doesnotexists",dataType: "jsonp",timeout: 5000,success: function (parsed_json) {console.log(parsed_json);},error: function (parsedjson, textStatus, errorThrown) {console.log("parsedJson: " + JSON.stringify(parsedjson));$('body').append(    "parsedJson status: " + parsedjson.status + '</br>' +     "errorStatus: " + textStatus + '</br>' +     "errorThrown: " + errorThrown);         }});

jsfiddle - Handle Errors with jquery ajax call and JSONP dataType - Error 404