I'm facing a problem with my app. It's in a JS-PHP environment. I've made a minimal reproduced example below.
script.js:
function postToHandler(){
let xhr = new XMLHttpRequest();
xhr.open("POST", "./apps/researcher.php");
let form = new FormData();
form.append('triggerLoop', "mockData");
xhr.send(form);
activateGlobalsListener();
}
function activateGlobalsListener(){
setInterval(function(){
let xhr_listen = new XMLHttpRequest();
xhr_listen.open("POST", "./apps/researcher.php");
let form = new FormData();
form.append('listen', "mockData");
xhr_listen.send(form);
xhr_listen.onreadystatechange = function (){
if(xhr_listen.readyState === XMLHttpRequest.DONE){
console.log("RECEIVED LISTEN DATA");
console.log(xhr_listen.response);
}
}
},1000);
}
And here is the php file
<?php
//SOURCE OF PROBLEM BELOW: When I uncomment the session_start line, the listening process stops working
//session_start();
$_SESSION['globalVar'] = "undefinedData";
if (!empty($_POST['triggerLoop'])) {
for ($x = 0; $x < 10; $x++) {
$_SESSION['globalVar'] = getResult();
sleep(1);
}
}
//------------------------------------------------------
//Listen
if (!empty($_POST['listen'])) {
echo $_SESSION['globalVar'];
}
function getResult()
{
return rand(10, 100);
}
?>
My script.js file creates multiple XMLHttpRequests to the same researcher.php file.
The first request will initiate a loop within the PHP file. This loop will update a SESSION variable with a random int. There is a 1 second sleep call that also occurs during every iteration of that loop.
Then after the script.js has triggered this, my script.js file starts an interval (also every 1 second), where it will send a request to that same PHP file, attempting to read the value of that SESSION variable (which is supposed to get updated with a new value every 1 second).
But I find that the value of that SESSION variable is always the initial value with which it was defined.
So where am I wrong?
I have looked at similar questions on Stackexchange and some say that you should add a "session_start()" line at the top of the PHP file. But when I do that I've noticed a peculiar thing......the script.js is not getting the responses (within the setInterval) immediately. It seems to get those responses delayed....only after the entire PHP loop is finished. Why though? Why does starting a session have that effect?
Other similar questions also say that you should add a redirect call every time a SESSION variable is updated. Like
header("location:./Researcher.php");
To redirect the file to itself? But if I do that, won't it break the current loop and all the ongoing processes?