44

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)?

2
  • 7
    While adequate answers were provided for my problem, I'm still baffled that the devs would program silent failure into $.getJSON...wtf jQuery guys?
    – Dan Burton
    Mar 30, 2011 at 23:26
  • 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.
    – jpaugh
    Apr 24, 2018 at 14:36

5 Answers 5

89

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).

4
  • 3
    Note that .error is deprecated - best to use .fail instead: api.jquery.com/jQuery.ajax
    – micapam
    Apr 11, 2013 at 2:44
  • 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?
    – ncubica
    Jun 5, 2013 at 19:44
  • 1
    @superluminary: use fail(function(d, textStatus, error)... I've just edited the answer. Oct 7, 2013 at 21:13
  • 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. Dec 15, 2015 at 18:14
29

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
});
3
  • 3
    +1 the shorthand $.getJSON was convenient, but not flexible enough to be truly useful. /sigh.
    – Dan Burton
    Mar 30, 2011 at 23:24
  • 1
    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?
    – semperos
    Jan 18, 2012 at 19:22
  • 3
    The shorthand is useful with the new promise syntax $.getJSON(...).error(function() {...})
    – Paul Tyng
    Nov 3, 2012 at 19:29
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.)

1
  • +1 Apparently $.ajax also catches the parse error and sends information about it to the error callback, as mentioned by Håvard.
    – Dan Burton
    Mar 30, 2011 at 23:25
0

You should have a look at the docs for this API... it has a .error on it.

http://api.jquery.com/jQuery.getJSON/

1
  • 1
    The .success(), .error(), and .complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. Feb 27, 2014 at 10:16
0

If you're requesting JSONP as the response, you will get a silent fail if there is no response (e.g. network outage). See this thread for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.