javascriptjqueryjsonp

How do I catch jQuery $.getJSON (or $.ajax with datatype set to 'jsonp') error when using JSONP?


Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):

jQuery.ajax({
    type: "GET",
    url: handlerURL,
    dataType: "jsonp",
    success: function(results){
        alert("Success!");
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert("Error");
    }
});

And also:

jQuery.getJSON(handlerURL + "&callback=?", 
    function(jsonResult){
        alert("Success!");
    });

I've also tried adding the $.ajaxError but that didn't work either:

jQuery(document).ajaxError(function(event, request, settings){
   alert("Error");
});

Solution

  • It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.

    After searching their bug tracker, there's a patch which may be a possible solution using a timeout callback. See bug report #3442. If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.