Display data from long running PHP script with jQuery

When a PHP script is executed for a long time and it is not clear what it is happening, such as a long loop, a prolonged processing, rainy weather, or other magical things. That is, the desire to see what is happening with the data and at what stage of implementation is a script program. One of the options to use function flush() which clears PHP output buffer and all its contents are sent to the user's browser.

<?
header('Content-Type: text/plain; charset=utf-8');
//unlimited script run time
set_time_limit(0);
//loop
for($i=0;$i<1000;$i++){
	//data output
	echo "\nloop: $i progress: ".round($i/10)."%";
	//clear and send PHP output buffer
	flush();
	//pause for clarity
	usleep(100000);
}

Another option is to use a script to write data to a separate file and load this file from time to time in the browser. You will need to write data file from the script:

<?
set_time_limit(0);
for($i=0;$i<1000;$i++){
	//writing data to the file log.txt, you need to set file write permissions
	file_put_contents('log.txt', "loop: $i<br> progress: ".round($i/10)."%");
	//pause for clarity
	usleep(100000);
}

Further data file will load jQuery load function:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>Progress</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var reload = setInterval(
	function(){
		//load data from file and display in element id="progress"
		$('#progress').load('log.txt');
	}, 1000); //every second
});	
</script>
</head>
<body>
	<div id="progress"></div>
</body>
</html>
This entry was posted in Programming and tagged , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.