Monday, August 31, 2015

Automatically update web page contents inside a < div > on a regular basis


It took me quite a while to figure this out.  But in the end, it was quite simple. Along the way I discovered that Chrome's development screen is very helpful.  You can see source HTML and generated HTML and put breakpoints in javascript code.

What I wanted to accomplish was to have certain areas of my web page updated automatically on a regular basis.  The contents were generated by a Perl CGI script, so the web page had to re-execute the Perl script each time.

When I started investigating, I was trying to stick to purely JavaScript since that's what I'm familiar with.  However, I soon discovered that jQuery is pretty much required and is basically the same as using JavaScript.

So, to get to the nitty gritty.  The way I implemented it was to define a function in the <head> section of my HTML page.  First, you have to point the script to a jQuery source
  <script src='http://code.jquery.com/jquery-latest.js'></script>
Then define your function:
  <script>
      setInterval(
        function() {
          $.post('cgi-bin/script.cgi', 
            function(data){ $('#myDIV').html(data); }
          ); }, 1000 );
  </script>
So, to break down the above code line by line:

  • setInterval is a jQuery function that tells it how often to execute the function inside
  • function() is the definition of the function to call the CGI
  • $.post executes the specified script
  • function(data) { $('#pingSliders').html(data); }  updates the <div> called #myDIV with the output of the script.  
  • 1000 is a parameter to the setInterval function that specifies the frequency in milliseconds that the script is run


The CGI script is up to you but it just needs to generate standard HTML.  This is included inline in your page where ever you place your<div> section.

The one detail that tripped me up is that the first print statement that your CGI script outputs MUST be:
print "Content-type: text/html\r\n\r\n";
If it's not that, then the lines that follow are not understood to be HTML.

You can also create multiple <script> sections to define methods for updating different sections of your web page at the same time and at different frequencies.

You can see my implementation on my web page here:  http://www.tookay.info.  Let me know what you think!

Here's the whole HTML implementation.  It's really that simple.

<html>
<head>
  <title>Sample Update</title>
  <link type="text/css" rel="stylesheet" href="css/style.css"/>
  <script src='http://code.jquery.com/jquery-latest.js'></script>
  <script>
      setInterval(
        function() {
          $.post('cgi-bin/script.cgi', 
            function(data){ $('#myDIV').html(data); }
          ); }, 1000 );
  </script>
</head>

<body> 
     <div id='myDIV'></div>
</body>
</html>

Check out my YouTube channel:   
www.youtube.com/KedarWarriner


No comments:

Post a Comment