How do I handle 500 errors when using jQuery's getJSON?
There have been a couple of questions about error handling with getJSON()
and JSONP, but I'm not working with JSONP, just ordinary JSON.
Another answer suggests using .ajaxSetup()
before calling getJSON()
, so I tried this:
$.ajaxSetup({
"error":function() {
alert('Error!');
}});
$.getJSON('/book_results/', function(data) { # etc
But I find that the alert always triggers, even when the result is well-formed.
Any ideas?
Please do the following. Pseduo code:
If you are using the jquery version 1.5 or higher you can use the new methods .success(function), .error(function) and .complete(function)
Example from http://api.jquery.com/jQuery.get/
Works perfect for me. I hope this helps
Using jQuery 3.2.1:
you can see it on jquery api getJSON: http://api.jquery.com/jQuery.getJSON/
//jquery1.5+ the fail callback will trigger when text is not the correct json string or any other fail solutions
The
getJSON
method does not natively return errors but you could dive into the xhr object that is returned as a parameter in the callback.The
getJSON
method is a shorthand function forjQuery.ajax
. UsingjQuery.ajax
you can easily achieve error handling: