Apologies if this seems like a repeat question but I’m having a different doubt now.
Basically I have a PHP file that is set up like this:
Pretty straight forward. It is supposed to update a global variable (globalVar) from inside a loop every 1 second, using a random int.
I have a script.js file which creates seperate XmlHttpRequests to this php file. The first request will trigger the loop (which updates globalVar).
Immediately after that, script.js will start an interval where it will start sending new XHRs to the php file every second and attempt to read the value of globalVar.
function postToHandler(){
console.log("Posting to handler");
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
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.withCredentials = true;
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);
}
I was expecting the XHRs in the setInterval to return random ints, but they always return “undefined”.
Which makes me wonder if this is happening because the XHRs are creating their own unique sessions? As in, the first XHR creates session#1. And then the subsequent XHRs create session#2…session#3…etc. And that’s why those subsequent XHRs are not able to access the global variables of session#1? Because they are existing on different sessions?