6

Possible Duplicate:
JavaScript: How to detect that the Internet connection is offline?

In facebook, when you loose the internet connection, you see a message "No internet connection. Try again?" and you are changed from online to offline. I want that in my website. How can I do that?

Community
  • 1
  • 1
user1763032
  • 427
  • 9
  • 24
  • 2
    Send a ping to the server. If no response, then they are offline and alert them using Javascript. – Tim Withers Dec 30 '12 at 04:40
  • 2
    As of HTML5, you can use [`window.navigator.onLine`](https://developer.mozilla.org/en-US/docs/DOM/window.navigator.onLine), though not fully compatible – jeremy Dec 30 '12 at 04:42

2 Answers2

4

This should work, but I would probably handle it differently. It just sends a query to a page on your server every 15 seconds. If the query fails, then it is probably offline (either you or the server).

function checkOnline(){
    $.ajax({
        url: "test.php",
    }).done(function( html ) {
        if(html=='ok')
            setTimeout('checkOnline()',15000);
        else
            alert('Error');
    }).fail(function(){
        alert('Offline');
    });
}

test.php

<?php exit('ok'); ?>

I would personally attach a fail function to my other Ajax or polling queries. If those failed, I would trigger the Offline message and cease further polling or queries until the page was reloaded or after a certain time interval. No sense in just polling the server for the heck of it.

Tim Withers
  • 12,072
  • 5
  • 43
  • 67
  • Thanks . what about changing the user from online to offline in my MySql database. Is it possible. How does facebook do that? – user1763032 Dec 30 '12 at 06:08
3

Run a periodical ajax request to your server. If the request fails, the ajax engine would call a "fail" callback.

But in real life, you would probably attach a "fail" javascript callback to all requests to server side, and it would fire upon a failed request.

Sych
  • 1,849
  • 16
  • 19