3

I need some conditional jquery to check internet availability as below and if available it refresh the page and then wait for same amount of time as of refresh and do the same activity again like in while loop

<script>
var a=navigator.onLine;
 if(a){
    <META HTTP-EQUIV="refresh" CONTENT="10">
 }else{
  alert('ofline');
 }
</script>

Please help regarding above lines of code.

Thank you

Noman Uddin
  • 103
  • 1
  • 11
  • 2
    Not only does this not have anything to do with Django, but you didn't even state what the problem is. – Daniel Roseman Dec 08 '14 at 16:52
  • I am using this jquery in Django Template. From general perspective you are right about django, Secondly problem is I need some conditional jquery for the above stated purpose and I found some piece of code but it is not working so I share it. @DanielRoseman – Noman Uddin Dec 09 '14 at 11:21

1 Answers1

4

One way to check for connectivity would be to set up a small png image or file on your same web server (same domain as current page) and test if you can connect to that file. Setting a timeout on an ajax call will trigger its error handler if no response is received after a number of seconds.

function check_connect()

    var testURL = "/somefile.png"
    var waitTime = 15000  // recheck every 15 seconds

    $.ajax({
      type: 'GET',
      url: testURL,
      timeout: 5000,  // allow this many milisecs for network connect to succeed
      success: function(data) {
        // we have a connection, reload page then try again after waitTime
        location.reload();  // reloads entire page
        window.setTimeout(check_connect, waitTime)  // try again after waitTime miliseconds
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        // no connection, try again after waitTime
        window.setTimeout(check_connect, waitTime) 
      }
      });

There may be other helpful answers here JQuery Ajax - How to Detect Network Connection error when making Ajax call

And more about jquery's ajax settings such as timeout are here http://api.jquery.com/jquery.ajax/

Community
  • 1
  • 1
brobas
  • 596
  • 4
  • 5