Error handling in getJSON calls

JqueryCross DomainJsonpGetjson

Jquery Problem Overview


How can you handle errors in a getJSON call? Im trying to reference a cross-domain script service using jsonp, how do you register an error method?

Jquery Solutions


Solution 1 - Jquery

$.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

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

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

'generic' would be something like:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });

Solution 2 - Jquery

Someone give Luciano these points :) I just tested his answer -had a similar question- and worked perfectly...

I even add my 50 cents:

.error(function(jqXHR, textStatus, errorThrown) {
		console.log("error " + textStatus);
		console.log("incoming Text " + jqXHR.responseText);
	})

Solution 3 - Jquery

Here's my addition.

From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html and the official source

"The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."

I did that and here is Luciano's updated code snippet:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });

And with error description plus showing all json data as a string:

$.getJSON("example.json", function(data) {
  alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });

If you don't like alerts, substitute them with console.log

$.getJSON("example.json", function(data) {
  console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });

Solution 4 - Jquery

I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question

The getJSON structure is as follows (found on [http://api.jqueri.com](http://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success-data--textStatus--jqXHR- "jquery api for getJSON")):

$(selector).getJSON(url,data,success(data,status,xhr))

most people implement that using

$.getJSON(url, datatosend, function(data){
    //do something with the data
});

where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.

You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object ([found on w3schools](http://www.w3schools.com/jquery/ajax_getjson.asp "w3schools link to getJSON"))

$.getJSON(url, datatosend, function(data, status, xhr){
    if (status == "success"){
        //do something with the data
    }else if (status == "timeout"){
        alert("Something is wrong with the connection");
    }else if (status == "error" || status == "parsererror" ){
        alert("An error occured");
    }else{
        alert("datatosend did not change");
    }         
});

This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.

Hope this helps someone still looking for an answer to this question.

Solution 5 - Jquery

$.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })

It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback

Solution 6 - Jquery

Why not

getJSON('get.php',{cmd:"1", typeID:$('#typesSelect')},function(data) {
	// ...
});

function getJSON(url,params,callback) {
	return $.getJSON(url,params,callback)
		.fail(function(jqXMLHttpRequest,textStatus,errorThrown) {
			console.dir(jqXMLHttpRequest);
			alert('Ajax data request failed: "'+textStatus+':'+errorThrown+'" - see javascript console for details.');
		})
}

??

For details on the used .fail() method (jQuery 1.5+), see http://api.jquery.com/jQuery.ajax/#jqXHR

Since the jqXHR is returned by the function, a chaining like

$.when(getJSON(...)).then(function() { ... });

is possible.

Solution 7 - Jquery

I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.

If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)

try:
    snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
    db.session.delete(snip)
    db.session.commit()
    return jsonify(success=True)
except Exception, e:
    logging.debug(e)
    return jsonify(error="Sorry, we couldn't delete that clip.")

Then you can check on Javascript like this;

$.getJSON('/ajax/deleteSnip/' + data_id,
    function(data){
    console.log(data);
    if (data.success === true) {
       console.log("successfully deleted snip");
       $('.snippet[data-id="' + data_id + '"]').slideUp();
    }
    else {
       //only shows if the data object was returned
    }
});

Solution 8 - Jquery

In some cases, you may run into a problem of synchronization with this method. I wrote the callback call inside a setTimeout function, and it worked synchronously just fine =)

E.G:

function obterJson(callback) {


    jqxhr = $.getJSON(window.location.href + "js/data.json", function(data) {

    setTimeout(function(){
        callback(data);
    },0);
}

Solution 9 - Jquery

This is quite an old thread, but it does come up in Google search, so I thought I would add a jQuery 3 answer using promises. This snippet also shows:

  • You no longer need to switch to $.ajax to pass in your bearer token
  • Uses .then() to make sure you can process synchronously any outcome (I was coming across this problem .always() callback firing too soon - although I'm not sure that was 100% true)
  • I'm using .always() to simply show the outcome whether positive or negative
  • In the .always() function I'm updating two targets with the HTTP Status code and message body

The code snippet is:

    $.getJSON({
         url: "https://myurl.com/api",
         headers: { "Authorization": "Bearer " + user.access_token}
    }).then().always(   function (data, textStatus) {
        $("#txtAPIStatus").html(data.status);
        $("#txtAPIValue").html(data.responseText);
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAjayView Question on Stackoverflow
Solution 1 - JqueryLuciano CostaView Answer on Stackoverflow
Solution 2 - JqueryfrenetixView Answer on Stackoverflow
Solution 3 - Jqueryuser2314737View Answer on Stackoverflow
Solution 4 - JqueryTom GroentjesView Answer on Stackoverflow
Solution 5 - JqueryPavlo O.View Answer on Stackoverflow
Solution 6 - Jqueryphil294View Answer on Stackoverflow
Solution 7 - JqueryNick WoodhamsView Answer on Stackoverflow
Solution 8 - JqueryAlex AlonsoView Answer on Stackoverflow
Solution 9 - JqueryFrom OrboniaView Answer on Stackoverflow