Reputation: 325
var refreshId_hxlatestposts = setInterval(function() {
var el = $("#hxlatestposts");
var req = $.get("example.php");
el.fadeOut('slow', function () {
req.done(function( data ){
el.html(data).fadeIn('slow');
});
});
}, 60000);
This is what i use to refresh a div every minute, sometimes it gets hung up when the site it is getting the feed from is down or something. I'd like to some how have a timeout so if it cannot load the php file in X seconds then return 'Fail to load'.
Upvotes: 4
Views: 491
Reputation: 1350
jQuery's $.get is just a shorthand for $.ajax, which is used when more flexibility is required (in your case, yes)
Replace $.get("example.php");
with:
$.ajax({
type: "GET",
url: "example.php",
timeout: X*1000,
}).done(function(data) {
el.fadeOut('slow', function () {
el.html(data).fadeIn('slow');
});
}, 60000);
});
where X
is number of seconds you would want it to wait (timeout)
Upvotes: 1
Reputation: 1986
jQuery documentation (.ajaxSetup()) suggests using .ajaxSetup()
to set the value for timeout
, instead of using it in individual requests.
You can use request.fail()
to register a function in case of a failed request.
$.ajaxSetup({
timeout: 5000
});
var refreshId_hxlatestposts = setInterval(function() {
var el = $("#hxlatestposts");
var req = $.get("example.php");
el.fadeOut('slow', function() {
req.done(function(data) {
el.html(data).fadeIn('slow');
});
req.fail(function(jqXHR, textStatus) {
el.html('Fail to load').fadeIn('slow');
});
});
}, 60000);
Upvotes: 2
Reputation: 14319
You'll want to check the status of the incoming response to ensure that the service returned a 200 Ok status. This is more reliable than just waiting for a timeout-- you will know if it's good data or not an can decide to retry by putting your timeout in the complete functions.
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
//handle status codes etc.
// then set your timeout
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
//handle status codes etc.
// then set your timeout
},
// OR
fail: function( xhr, textStatus ){
//retry code or timeout
}
});
Upvotes: 1
Reputation: 95054
Nice use of deferred objects.
If you replace $.get
with $.ajax
, you can add a timeout.
var req = $.ajax({
url: "example.php",
type: "GET",
timeout: 5000 // 5 seconds
});
and then add a fail handler
req.done(function(){...}).fail(function(){
alert("failed to load");
});
Upvotes: 2