Reputation: 571
I'm trying to set up a display screen for the floor info which is a simple web page. The ajax call is for updating the screen every 10 seconds according to the admin page which the client is using for updating the info.
My problem is when there is no internet connection, the display would still be updated and shows nothing. Is there any way I can alter the code below to say if there is an internet connection then update the database, if there no network connection then reset the timer and do nothing.
<script type="text/javascript">
// Run the AJAX call to grab the data once
$.ajax({
type: "POST",
url: "ajax/getMessages.php?section=1",
data: "",
complete: function(data){
//print result in targetDiv
$('#content_1').html(data.responseText);
}
});
// Then run the same script on a 10-second timer
setInterval(function(){
$.ajax({
type: "POST",
url: "ajax/getMessages.php?section=1",
data: "",
complete: function(data){
//print result in targetDiv
$('#content_1').html(data.responseText);
}
});
},10000);
</script>
Upvotes: 0
Views: 216
Reputation: 198204
You can use the textStatus
from complete(jqXHR, textStatus)
which will be any of the following: "success", "notmodified", "error", "timeout", "abort", or "parsererror".
$.ajax({
type: "POST",
url: "ajax/getMessages.php?section=1",
data: "",
complete: function(data, textStatus)
{
//print result in targetDiv if successfull
if (textStatus == 'success')
{
$('#content_1').html( + ': ' + data.responseText);
}
}
});
See http://api.jquery.com/jQuery.ajax/
Upvotes: 1
Reputation: 101533
There are probably other ways to do it, but this will work: check whether data.responseText
has anything in it:
if(data.responseText.length)
{
// Display page
}
In your complete:
function, like so:
complete: function(data){
if(data.responseText)
{
$('#content_1').html(data.responseText);
}
}
A better way to do this would be to use success:
instead of complete:
, as the former is only fired if the AJAX request completes successfully, meaning you don't have to check for data.length
.
// Run the AJAX call to grab the data once
$.ajax({
type: "POST",
url: "ajax/getMessages.php?section=1",
data: "",
success: function(data) {
// Print result in targetDiv
$('#content_1').html(data.responseText);
},
error: function() {
// Error handling code
}
});
// Then run the same script on a 10-second timer
setInterval(function() {
$.ajax({
type: "POST",
url: "ajax/getMessages.php?section=1",
data: "",
success: function(data) {
// Print result in targetDiv
$('#content_1').html(data.responseText);
},
error: function() {
// Error handling code
}
});
}, 10000);
Upvotes: 2
Reputation: 25786
var timer = setInterval(function(){
$.ajax({
type: "POST",
url: "ajax/getMessages.php?section=1",
data: "",
success: function(data){
//print result in targetDiv
$('#content_1').html(data.responseText);
},
error: function(){ clearInterval( timer ) }
});
},10000);
Upvotes: 0