Arturo Arturo - 9 months ago 117
Ajax Question

Javascript: conditions when $ 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

. In what conditions should I expect the
be called?

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

Answer Source

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.