I need to execute an AjaX call to a PHP script with a long execution time. My goal is to display a progress status of this execution.
The idea is to create an AjaX call to periodically ask the server about the status of the execution. The progress status is stored into $_SESSION['progress']
, initially set to 0
and changed from script during execution.
Here's my code on client and server side.
Client-side
// invoke the script (ie. with button)
$('#start').click(function()
{
$.ajax
({
url: "long-script.php"
});
});
// check progress periodically
setInterval(progress, 100);
function progress()
{
$.ajax
({
dataType: "json",
url: "progress.php",
success: function(data)
{
console.log(data);
}
});
}
long-script.php
// just an example to emulate execution
sleep(1);
$_SESSION['progress']=30;
sleep(1);
$_SESSION['progress']=70;
sleep(1);
$_SESSION['progress']=100;
progress.php
header('Content-Type: application/json');
echo json_encode($_SESSION['progress']);
The problem is that console.log()
in progress function outputs 0
before the script execution, stops outputing data during the execution, and finally outputs 100
when the script is terminated. What am I missing?