Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to add a facebook functionality of displaying a message when my user loses the internet connection [duplicate]

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?

like image 947
user1763032 Avatar asked Dec 30 '12 04:12

user1763032


2 Answers

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.

like image 164
Tim Withers Avatar answered Oct 24 '22 05:10

Tim Withers


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.

like image 26
Sych Avatar answered Oct 24 '22 06:10

Sych