Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does $.getJSON silently fail?

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

like image 341
Dan Burton Avatar asked Mar 30 '11 21:03

Dan Burton


People also ask

What are the arguments of getJSON method?

It is a callback function that executes on the successful server request. It also has three parameters that are data, status, and xhr in which data contains the data returned from the server, status represents the request status like "success", "error", etc., and the xhr contains the XMLHttpRequest object.

Is getJSON an Ajax call?

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.


2 Answers

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

like image 126
Mr Shoubs Avatar answered Sep 22 '22 22:09

Mr Shoubs


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 }); 
like image 30
Håvard Avatar answered Sep 22 '22 22:09

Håvard