Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"); }); 

Thanks in advance for any replies!

like image 899
Andy May Avatar asked Nov 21 '08 19:11

Andy May


People also ask

Can Jsonp be used with ajax?

JSONP allows you to sidestep the same-origin policy and to some extent make cross-domain Ajax calls. It's not a silver bullet, and it certainly has its issues, but in some cases it can prove invaluable when fetching data from a different origin.

What is the difference between getJSON and ajax in jQuery?

getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).

What is Jsonp in ajax?

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.

How jQuery read data from JSON file?

To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery. getJSON( ) method loads JSON data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server.


1 Answers

Here's my extensive answer to a similar question.

Here's the code:

jQuery.getJSON(handlerURL + "&callback=?",      function(jsonResult){         alert("Success!");     }) .done(function() { alert('getJSON request succeeded!'); }) .fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); }) .always(function() { alert('getJSON request ended!'); }); 
like image 188
user2314737 Avatar answered Oct 25 '22 08:10

user2314737