Grow your CSS skills. Land your dream job.

Last updated on:

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

Reference URL


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

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".