Error handling in getJSON calls

Ajay picture Ajay · Nov 16, 2009 · Viewed 233.9k times · Source

How can you handle errors in a getJSON call? Im trying to reference a cross-domain script service using jsonp, how do you register an error method?

Answer

Luciano Costa picture Luciano Costa · Apr 5, 2011

$.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

'generic' would be something like:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });