user411103
user411103

Reputation:

Javascript: conditions when $.getJSON.fail() is called

I am making requests to an API using the code below. I have made different tests including failures (wrong URL, no connectivity,...) and all the responses come from the done(). In what conditions should I expect the fail() be called?

  $.getJSON("http://myapi.com/", {
    action: "register",
    username: email,
    password: password
  });
  .done(function(response) { console.log(response); })
  .fail(function(jqxhr, textStatus, error) { console.log(textStatus); });

Upvotes: 0

Views: 182

Answers (1)

Taplar
Taplar

Reputation: 24965

Typically fail() will fire if the response is not a 'good' response code, such as a non 2xx or 3xx code. Otherwise, it can also fire if something in the request failed to parse. Such as if you told it you were expecting json returned and the response was not (valid) json. In which case the parse error should also result in fail() being fired (iirc). @charlietfl also brought up that request timeouts can also cause fail() to fire. I'm sure though this is not a complete list.

Upvotes: 1

Related Questions