Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching a JSONP error on a cross-domain request

I'm using jQuery.getJSON() on a URL (different domain) which may not exist. Is there a way for me to catch the error "Failed to load resource"? It seems that try/catch doesn't work because of the asynchronous nature of this call.

I can't use jQuery.ajax()'s "error:" either. From the documetation:

Note: This handler is not called for cross-domain script and JSONP requests.

like image 776
Matthew Simoneau Avatar asked Feb 07 '11 17:02

Matthew Simoneau


People also ask

What is JSONP error?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

Does JSONP still work?

JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.

What is the one reason to avoid using JSONP in a web application?

JSONP has some other limitations, too: It can only be used for GET requests, and there's no general way to prevent cross-site request forgeries*. It's bad for private data, since any site on the web could hijack a JSONP response if the URL is known.

Why is JSONP insecure?

JSONP is vulnerable to the data source replacing the innocuous function call with malicious code, which is why it has been superseded by cross-origin resource sharing (available since 2009) in modern applications.


1 Answers

If you have an idea of the worst case delay of a successful result returning from the remote service, you can use a timeout mechanism to determine if there was an error or not.

var cbSuccess = false;
$.ajax({
   url: 'http://example.com/.../service.php?callback=?',
   type: 'get',
   dataType: 'json',
   success: function(data) {
              cbSuccess = true;
            }
});
setTimeout(function(){ 
        if(!cbSuccess) { alert("failed"); } 
    }, 2000); // assuming 2sec is the max wait time for results
like image 176
Joy Dutta Avatar answered Sep 22 '22 02:09

Joy Dutta