Why does $.getJSON silently fail?

38,389

Solution 1

you can use

        function name() {
            $.getJSON("", function(d) {
                alert("success");
            }).done(function(d) {
                alert("done");
            }).fail(function(d) {
                alert("error");
            }).always(function(d) {
                alert("complete");
            });
        }

If you want to see the cause of the error, use the full version

function name() {
    $.getJSON("", function(d) {
        alert("success");
    }).fail( function(d, textStatus, error) {
        console.error("getJSON failed, status: " + textStatus + ", error: "+error)
    });
}

If your JSON is not well-formed, you will see something like

getJSON failed, status: parsererror, error: SyntaxError: JSON Parse error: Unrecognized token '/'

If the URL is wrong, you will see something like

getJSON failed, status: error, error: Not Found

If you are trying to get JSON from another domain, violating the Same-origin policy, this approach returns an empty message. Note that you can work around the Same-origin policy by using JSONP (which has it's limitations) or the preferred method of Cross-origin Resource Sharing (CORS).

Solution 2

Straight from the documentation:

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.

As the documentation page says, getJSON is simply a shorthand method for

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

To get failure behavior, you can use $.ajax like this:

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

Solution 3

You can use $.ajax instead, and set the dataType options to "json". From the documentation:

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

Share:
38,389

Related videos on Youtube

Dan Burton
Author by

Dan Burton

Updated on September 08, 2020

Comments

  • Dan Burton
    Dan Burton over 3 years

    It seems very inconvenient that jQuery's $.getJSON silently fails when the data returned is not valid JSON. Why was this implemented with silent failure? What is the easiest way to perform getJSON with better failure behavior (e.g. throw an exception, console.log(), or whatever)?

    • Dan Burton
      Dan Burton about 13 years
      While adequate answers were provided for my problem, I'm still baffled that the devs would program silent failure into $.getJSON...wtf jQuery guys?
    • jpaugh
      jpaugh about 6 years
      It's because jQuery is old. Before JS had proper debugging tools, or even a console to log to, every failure was either silent, added to the page, or displayed in an alert(). Throwing exceptions would have halted the code, and prevented any possible recovery by client code later on; unless every bit of 3rd-party code were wrapped in a try-catch block by the developer.
  • Dan Burton
    Dan Burton about 13 years
    +1 the shorthand $.getJSON was convenient, but not flexible enough to be truly useful. /sigh.
  • Dan Burton
    Dan Burton about 13 years
    +1 Apparently $.ajax also catches the parse error and sends information about it to the error callback, as mentioned by Håvard.
  • semperos
    semperos over 12 years
    The documentation is clear, but this doesn't explain why it silently fails. What is the rationale behind the layer responsible for parsing a String into a JavaScript Object being silent about errors by default?
  • Paul Tyng
    Paul Tyng over 11 years
    The shorthand is useful with the new promise syntax $.getJSON(...).error(function() {...})
  • micapam
    micapam about 11 years
    Note that .error is deprecated - best to use .fail instead: api.jquery.com/jQuery.ajax
  • ncubica
    ncubica almost 11 years
    Why you will use this? instead of ajax? while this is a wrap for ajax method right? So basically would be better use Ajax when you want to handle all this "status".. what do you think?
  • Sergey Orshanskiy
    Sergey Orshanskiy over 10 years
    @superluminary: use fail(function(d, textStatus, error)... I've just edited the answer.
  • Jim Bergman
    Jim Bergman about 10 years
    The .success(), .error(), and .complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8.
  • Michael Blankenship
    Michael Blankenship over 8 years
    In the case where this is a CORS-related issue (as it was in mine) you will get textStatus='error' and error='' so I'd called this a JSON fail in the design. It should report something back to the developer in this case. Adding the CORS-related response header for my server side fixed this issue and immediately allowed my client to now see the correct JSON returned.