McFiddlyWiddly McFiddlyWiddly - 1 month ago 14
Ajax Question

How to handle error in ajax's $get with anonymous function?

I want to write an ajax function like this

$.get("./v1/user/"+username, function(response) {
document.getElementById("username").innerHTML=response.username;
});


and on failure, I want to change style property of some other element.

How do I write a .fail or similar function here to handle the error?

Answer

How do I write a .fail or similar function here to handle the error?

You can use jQuery deferred.fail() or at versions 3.0+ .fail() or .catch()

$.get("./v1/user/"+username)
.then(function(response) {
    document.getElementById("username").innerHTML=response.username;
})
.fail(function(jqxhr, textStatus, errorThrown) {
  // do stuff
})