A Web Design Community curated by Chris Coyier

Code Snippets Gallery

Code Snippets > jQuery > jQuery JSON getting with error catching Submit one!

jQuery JSON getting with error catching

jQuery has a built in function called getJSON() to help making AJAX requests for JSON data easier. It normally works great, but if that function gets invalid data (or nothing) back, the callback function will not fire. If there is a legitimate risk of that, you can do this instead to catch for those errors.

$.get('/path/to/url', function (data) {
  if( !data || data === ""){
    // error
    return;
  }
  var json;
  try {
    json = jQuery.parseJSON(data);
  } catch (e) {
    // error
    return;
  }

  // use json here

}, "text");

Reference URL

Leave a Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.