Php long running script to dynamically update html

This code is a work in progress and should never be used in a production environment without extensive testing!

First, the page that is loaded into the browser, it uses jQuery to receive status updates from ‘getstatus.php’ script

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Update Inventory</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
 
     var flag = false
     var stop = false;
 
$(function() {
    startProcess();
    getStatus();
 
 
});
 
function startProcess() {
 
    $("#done").load('updatestock.php', function() {
 
        flag = true;
 
    });
 
}
 
function getStatus() {
 
    if ( stop ) {return false;}
 
    $("#status").load('getstatus.php');
    setTimeout("getStatus()",2000);
 
	if ( flag ) {stop = true;}
 
}
 
</script>
 
<style type="text/css">
div {padding:0 0 0 50px;}
</style>
 
</head>
<body>
	<h1>Long Running Script</h1>
	<div id="done"></div>
	<div id="status"></div>
</body>
</html>

This is the long running script simulator

 
<?php
 
$fh = fopen('status.log', 'w'); 
//simulate work for 30 seconds
    while($i < 30) {
	fwrite($fh, time()."<br />\n");
      sleep(1);
      $i++;
    }
 
fclose($fh);
 
?>

And getstatus.php, the script that returns data to be appended to div

<?php
/*
this script is accessed by the html version of the updater, and spools the output to the screen 
so the user can see updated information as the the script runs.
*/
 
$page = file_get_contents('status.log');
echo $page;
 
?>

Try it here (buggy)

2 thoughts on “Php long running script to dynamically update html”

  1. I like the approach..but I don’t know why it won’t create the file until the loop finishes, even if I open and close the file inside the loop

    Thanks for sharing!

Leave a Reply

Your email address will not be published.