Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery.getJSON() error handling

I am using jquery.getJSON(), but I don't know how to do error handling. And these are some situations that I need to handle.

1) what if the returned data is null?

2) what if the returned data is not json parseable?

3) what if some error message is returned? For example, the server returned HTTP ERROR

like image 887
Cacheing Avatar asked Oct 03 '13 16:10

Cacheing


People also ask

What is jQuery getJSON?

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

What is the difference between getJSON and Ajax in jQuery?

getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).

How jQuery read data from JSON file?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

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.


1 Answers

Since the $.getJSON() returns a promise object uou can use the .fail() promise callback for case 2 and 3... case 1 needs to be handled in the success callback itself

jQuery.getJSON(...).fail(function(jqXHR, status, error){
    if(status == 'parseerror'){
        //not valid json
    } else {
        //some other error
    }
})
like image 91
Arun P Johny Avatar answered Oct 05 '22 16:10

Arun P Johny