I'm trying to make a certain div appear on my webpage whenever the user's internet connectivity has been lost.
To do this I'm using some Javascript to call a php file, this file echoes back "1". If the echo is received then the connection is active and the Javascript prints "connected" in the console.
If the echo is not received then the Javascript prints "disconnected" in the console, and the div appears (This div contains a message to let the user know they've lost connectivity). The div takes up the entire page, so it effectively freezes the page, preventing the user from interacting with it, that's exactly what I want to happen. This is the Javascript code I'm using:
var checkConnection = function checkConnection() {
$.ajax({
url: 'php_scripts/checkconnection.php',
type: "POST",
cache: false,
success: function() {
document.getElementById('openOfflineDIV').style.display = 'none';
console.log("connected"); },
error: function() {
document.getElementById('openOfflineDIV').style.display = 'block';
console.log("disconnected"); }
}).complete(function() {
setTimeout(checkConnection, 2000);
});
}
And this is the php file "checkconnection.php":
<?php echo '1'; ?>
As you can see, I have this function set to run every 2 seconds.
The problem I have is this: The function works perfectly on Chrome, Firefox, IE and Opera, but it shows the disconnected div repeatedly when I test it on Safari. I've tested it on several devices (laptops, android phones etc) and it works fine, but when I test it on my Ipad and Mac using Safari, the disconnected div appears roughly every 10 seconds, it stays disconnected for about 5 seconds, then the div disappears/connection is re-established, but then around 10 seconds later the div reappears, this goes on and on. I don't know what's causing it but it seems to be a problem specific to the Safari browser.
Does anybody know what could be causing this? I've tried extending the time that the function repeats from 2 seconds to 5 seconds and this seems to have reduced the frequency of the disconnected divs appearing, but it's still appearing very often.
Is there a better way to check for a live internet connection? I don't want to extend the time any further as ideally the connection check would run every second.
I'd really appreciate advice on how to fix this. Thank you in advance for any help with this.