new site();

Fire a function when a file size changes (jQuery)

2011-08-23

Note: there are probably better ways of doing this, even if you accept the premise of the article.

I'd been working on a bingo game to sharpen up my Ajax, and encountered what seemed like a simple problem: the game updates a file when a person gets bingo, and I wanted a message to appear on all the players' screens when this happened. The simplest way of doing this seemed to be to grab the file size and then continually poll it to see when it changes.

The obvious problem is that the only way to get the file size is with a server-side script, whereas all the handling of this information was intended to be client-side:

<?php 
    if(file_exists("bingo.xml")){  
           $size_bingo = filesize("bingo.xml");  
          echo $size_bingo; 
      }
?>

The above code echoes the file size, but if you try to put this into your JavaScript it will continually return the same value, even when the file size changes. Which isn't what I wanted.

Thankfully, this situation is exactly what Ajax is intended for--putting server-side code together with client-side code. Specifically, XMLHttpRequest can be used in this instance to run the desired PHP code and do whatever we like with the output. JQuery gives us an extremely simple way to get this done, if we put the above code into an external file named checksize.php and link to the jQuery library:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
   var checkinterval=self.setInterval ("loadBingoFile()", 3000);    
   trigger_temp =  <?php  $size_bingo = filesize("bingo.xml");  echo $size_bingo;  ?>

   function loadBingoFile(){       
      $.post("checksize.php", function(data) {
          if (data > trigger_temp) { 
              alert ("bingo");
              trigger_temp = data; 
                    clearInterval(checkinterval);
            }          
        });  
    } 
</script>

In the above code, we first establish that the loadBingoFile() function should run once every three seconds. Next, we put a benchmark file size into trigger_temp using the PHP code. Then $.post runs the external PHP file and sticks whatever it outputs in the data variable. Finally, the function compares the two variables--and if they are different, it pops up an alert, resets trigger_temp, and stops the continuous run of loadBingoFile().

Tags: