Search code examples
phpajaxlive

How to update variable output automatically in PHP?


I currently have a script that looks something like this:

<?php
$pattern = '/(?<=\=\s)([0-9]+)(?=\s\=)/';
$total = 0;
$matches;

$handle = @fopen("log.txt", "r");

if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {        
        if(preg_match($pattern, $buffer, $matches))
        {
            $total += intval($matches[0]);
        }       
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
echo $total;
?>

The thing is that the variable $total will update often with a brand new number. I want the number to automatically update on the page, without the user having to refresh. I think that I might need to use AJAX by the looks of it, but my AJAX is very weak. Can anybody help me? Thanks!


Solution

  • Quick and dirty:

    <html lang="en">
        <head>
            <script type="text/javascript" src="http://www.google.com/jsapi"></script>
            <script type="text/javascript">
                google.load('jquery', '1.4.2'); 
                google.load('jqueryui', '1.8.8');
            </script>
            <script type="text/javascript">
                $(document).ready(function() {
                    setInterval('get_counter()', 500);
                });
                function get_counter()
                {
                    $('.counter').load('PATH_TO_YOUR_PHP_SCRIPT');
                }
            </script>
        </head>
        <body>
            <h1>Counter</h1>
            <div class="counter"></div>
        </body>
    </html>