The jQuery ajax call always returns a jqXHR
object whether success or failure. It never returns null
or undefined
.
The success or failure can be seen via either the optional callback notification functions or via the returned jqXHR object which acts as a promise object and thus will get promise notifications about the ajax call's completion, success or failure.
Because the jqXHR object is also a promise object, your code can be simplified to just this:
setInterval(function() {
$.ajax({
url : "/favicon.ico", /* or other resource */
type : "HEAD"
}).done(function() {
location.reload();
});
}, 120000); /* 120000 ~> 2 minutes */
If you want to be notified of other situations besides just .done()
, you can use .fail()
, .always()
or .then()
.
If the ajax calls fails immediately, then the promise will be resolved as a failure (e.g rejected). Subsequent .fail()
or .always()
handlers attached to the promise object will still be called even if it has already failed.
Here's the relevant jQuery documentation:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the
Promise interface, giving them all the properties, methods, and
behavior of a Promise (see Deferred object for more information).
These methods take one or more function arguments that are called when
the $.ajax() request terminates. This allows you to assign multiple
callbacks on a single request, and even to assign callbacks after the
request may have completed. (If the request is already complete, the
callback is fired immediately.) Available Promise methods of the jqXHR
object include:
jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative
construct to the success callback option, the .done() method replaces
the deprecated jqXHR.success() method. Refer to deferred.done() for
implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An
alternative construct to the error callback option, the .fail() method
replaces the deprecated .error() method. Refer to deferred.fail() for
implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) {
}); An alternative construct to the complete callback option, the
.always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the
same as those of .done(): data, textStatus, and the jqXHR object. For
failed requests the arguments are the same as those of .fail(): the
jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR,
textStatus, errorThrown ) {}); Incorporates the functionality of the
.done() and .fail() methods, allowing (as of jQuery 1.8) the
underlying Promise to be manipulated. Refer to deferred.then() for
implementation details.