-1

I’m trying to run a Javascript function to check internet connectivity status. If the user is connected to the internet then I don’t want anything to happen on screen. But if the connection is lost then I want to show a div.

(This div will take up the entire screen (which will stop the user from interacting with the page in the background) until the connection is re-established. Once the connection is re-established, the div should automatically disappear and the user should be able to interact with the buttons on screen again.)

To achieve this, I have a Javascript function to check connectivity which runs every second. It does this by using an AJAX post to a PHP file, the PHP file echos “1” back to the Javascript, if the function receives this “1” back, then it knows the connection is active, if it doesn’t receive it then it knows the connection is broken and it should show the div.

The div is called “openOfflineDIV”.

This is my Javascript:

   function checkConnection() {

    if($.ajax({
         url: 'php_scripts/checkconnection.php',
        type: "POST",
       async: false
       }).responseText == "1"){
           console.log("Connection active");       
         openOfflineDIV.style.visibility = 'hidden';
                               }
       else{
           console.log("Connection lost");
          openOfflineDIV.style.visibility = 'visible'; 
                                       }
       };

My PHP file:

<?php echo '1'; ?>

And the relevant parts of my HTML page:

//Head content (file containing “checkConnection();” is included here)
<body>

<script>
 setInterval(function(){
      checkConnection();
    },1000);
</script>

//Body content here

//DIV to show when connectivity is lost:
<div id="openOfflineDIV" class="modalOfflineDIVDialog">
<div id="mfs">
<div id="wrapper">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td align="center" valign="middle" class="alerttextbig">You have been disconnected from the internet!</td>
  </tr>
</table>
</div>
</div>
</div>
</body>

When I load up the page I see that the console writes “Connection active” every second. But I also get the following error in the console:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/

After looking into it it seems like it’s due to me having async = false in my Javascript, but when I remove this, it still doesn’t work.

I looked at the answers here: How do I return the response from an asynchronous call? And I have tried to implement the top answer by changing my code to this:

function checkConnection(result) {

    if(result == "1"){
           console.log("Connection active");
         openOfflineDIV.style.visibility = 'hidden';
       }
       else{
           console.log("Connection lost");
          openOfflineDIV.style.visibility = 'visible';    
                                       }
       }
       foo(checkConnection);

    function foo(callback){
    $.ajax({
         url: 'php_scripts/checkconnection.php',
        type: "POST",

      success: callback
    });
       }

This still isn’t working, it keeps writing “Connection lost” in the console, which makes me think that maybe it’s not waiting for the “1” to get returned from the PHP file.

I would really appreciate any help anyone could give me with this, I’ve tried implementing the answers I’ve found on here but so far have been unsuccessful, thank you in advance!

UPDATE

This is my current code using @andreas's answer:

   function checkConnection() {
    $.ajax({
        url: 'php_scripts/checkconnection.php',
        type: "POST",
        success: function() {
            $("#openOfflineDIV").hide();
            console.log("connected"); },
        error: function() {
            $("#openOfflineDIV").show();
            console.log("disconnected"); }
    }).complete(function() {
        setTimeout(checkConnection, 1000);
    });
}

$(document).ready(checkConnection); 

For some reason the div isn't appearing when the connection is lost, but "disconnected" does appear in the console every second, and "connected" appears whenever the connection is active.

UPDATE 2

This is another attempt to achieve the same result:

   function checkConnection() {
    $.ajax({
        url: 'php_scripts/checkconnection.php',
        type: "POST",
        success: function() {

    document.getElementById('openOfflineDIV').style.display = 'none';
    console.log("connected"); },

        error: function() {

    document.getElementById('openOfflineDIV').style.display = 'block';
//I have also tried: document.getElementById('openOfflineDIV').style.display = 'inline';
    console.log("disconnected"); }

    }).complete(function() {
        setTimeout(checkConnection, 1000);
    });
}

This method is half working, meaning that if I navigate to my webpage address with /#openOfflineDIV added to the end of it, then the page will load with the div showing on screen, this then disappears after a second once the function starts to run (which means the function is closing the div successfully once it realises the connection is active).

But the second part of the function isn't working, it's not displaying the div when the internet connection is lost. I've tried both the inline and block methods but neither is working. I'm very confused since the function is definitely able to hide the div successfully (which I think means my syntax for defining the div is correct).

Is there something I'm missing here? Might I need to include an extra script on the page or something like that to make this work?

Community
  • 1
  • 1
Emily
  • 1,151
  • 4
  • 21
  • 42
  • Firstly, your main questions asks how to do this synchronously, then you ask how to do it asynchronously, and in the code you tried your handling of asynchronous code is wrong, you're calling foo after already checking for a result that will come back from the inner call to checkConnection from the success of the ajax in foo – Jaromanda X Sep 12 '15 at 08:46

1 Answers1

0

This would be your skeletal structure to implement your on-/offline functionality

function checkConnection() {
    $.ajax({
        url: 'php_scripts/checkconnection.php',
        type: "POST",
        success: function() { $("#openOfflineDIV").hide(); },
        error: function() { $("#openOfflineDIV").show(); }
    }).complete(function () {    // this starts the next connection check in 1 second
        setTimeout(checkConnection, 1000);
    });
});

$(document).ready(checkConnection);   // trigger the inital connection check on DOMReady

I've made a small fiddle with it.
Just switch off your internet connection and the status should be updated accordingly (and a popup from jsfiddle for the same reason should appear^^)

Andreas
  • 21,535
  • 7
  • 47
  • 56
  • Hi @andreas Thank you for your answer, I'm trying to implement it but part of it doesn't seem to be working for me. I've added two console.logs ("connected" and "disconnected") and they're working correctly, so it seems like the connection check is working, but the div isn't appearing. I've added an update to the end of my question to show the code I have at the minute. I was wondering if you had any idea why the div isn't appearing, and is there another way to show/hide the div? Thanks again! – Emily Sep 13 '15 at 08:48
  • If the div is "hidden" with `display:none´ it should work. Is the id correct? Check the `$("#openOfflineDIV").length` property to see if the selector found something. If it is not null then there is something with your css. Check the developer tools. – Andreas Sep 13 '15 at 10:23
  • Hi @andreas I've tried different things including removing the ``#`` from the div name, but I can't see what's wrong with the code, and no errors are showing in the console (console.logs "connected" and "disconnected" are the only things showing). I've been trying a different method with your code and was wondering if you could take a look at it? I've posted it at the end of my question under "UPDATE 2". It's mostly working (the div is disappearing correctly) but for some reason I can't get the div to appear on its own without navigating directly to it. Thank you again for your help with this! – Emily Sep 14 '15 at 02:30
  • It's the same routine as the jQuery one but in vanilla js. Both should work. Especially if one does (div is hidden). Maybe you should post this as a new question as I'm running out of ideas... :( – Andreas Sep 14 '15 at 06:29
  • Hi @andreas thanks for your reply, I posted a new question and got an answer that solved the question. I'll mark yours as correct here, as the problem turned out to be a CSS issue and your code is sound. Thanks again. – Emily Sep 15 '15 at 06:35
  • You're welcome and I'm glad this issue has also been solved now :) – Andreas Sep 15 '15 at 06:36