3

Run the code if the page does not load

 2 years ago
source link: https://www.codesd.com/item/run-the-code-if-the-page-does-not-load.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Run the code if the page does not load

advertisements

I want to create a code that reloads a part of the page every 10 seconds and if it fails to reload (because of connection issue), then it plays a sound.

Is such thing possible using ajax and how? I have seen this type of feature in web chats before but never came across a code for it.


Try using setInterval function:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=windows-1250">
        <title>Test</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/css">
        <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript" language="JavaScript"></script>
        <style type="text/css">
        <!--
          .square {
              background-color: #AAAAAA;
              width: 250px;
              height: 100px;
          }
        //-->
        </style>
<script type="text/javascript" language="JavaScript">
  $(document).on('ready',function(){
    setInterval(updateDiv,10000);
  });

  function updateDiv(){
    $.ajax({
      url: 'getContent.php',
      success: function(data){
        $('.square').html(data);
      },
      error: function(){
        //Code to play a sound
        $('.square').html('<span style="color:red">Connection problems</span>');
      }
    });
  }
</script>
</head>
<body>
  <h1>The next div will be updated every 10 seconds</h1>
  <div class="square">
    Hello
  </div>
</body>
</html>

And the php script:

<?php
  echo "Updated value --> " . rand();
?>

To test, try renaming the php script (simulating connection problems) and rename to original name (getContent.php) to test correct situation again. Hope this helps.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK