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?
The problem is that the session is not written, until the script ends, or the session closes.
You need to remember that sessions, by default in php are stored as files on the system and is locked in run-time.
What you can do is change the long-script.php
file a bit.
session_start();
sleep(1);
$_SESSION['progress']=30;
session_write_close();
sleep(1);
session_start();
$_SESSION['progress']=70;
session_write_close();
sleep(1);
session_start();
$_SESSION['progress']=100;
session_write_close();
The idea is to write to the session after every progress changes.
Then you will need to start the session again.
This may be a wrong way to do this, but you can always look up the session functions in php. Take a look at this session_write_cloe