The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "Implementing an SVG Icon System" Nov 30 - 6:00 PM Eastern

jQuery JSON getting with error catching

Last updated on:

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
  var json;
  try {
    json = jQuery.parseJSON(data);
  } catch (e) {
    // error
  // use json here
}, "text");

Reference URL


  1. Agustín Amenabar L. (@baamenabar)
    Permalink to comment#

    Awesome! I was having this exact problem.
    No idea one could do try – catch on javascript.
    I’m always underestimating javascript :p

  2. Stig
    Permalink to comment#

    Nice one, thanks.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed