I have a javascript file which creates a XMLHttpRequest object and opens a connection to a PHP file and sends a form object to it. The Javascript file is like this:
let formData = new FormData();
formData.append("field1", ["mockdata1", "mockdata2"]);
let xhr = new XMLHttpRequest();
xhr.open("POST", "../phpscripts/agent.php");
xhr.send(formData);
The PHP file does something like this:
if( !empty( $_POST['field1'] )){
$result;
for($x=0; $x<someLimit; $x++){
//update $result
}
return $result;
}
So the PHP file queries another API and procedurally updates $result. The querying process takes time (each query to that API can range from 0.5 seconds to 2 seconds)
After it is done, it returns $result to the javascript file that sent the request. And this whole process takes quite some time because it makes multiple queries. There is a gap of around 10 seconds between when the javascript makes that xhr and when it gets the final result.
What I am trying to do is create some kind of a "listening system" inside that for-loop in the PHP file. So that the javascript file can read the current status of $result (as it builds up inside the for-loop) in predetermined intervals.
What is the best way to do this? Because the XHR object will only be received by javascript once that php for-loop is over and it returns $result.
Is there some way of creating a "stream" instead of a one-time request and return (which is how XHR works)? So that I can create a setInterval in the Javascript file which reads that stream every second and gets the current state of $result.
I have thoguht about making a 2nd XHR object but I don't know how to make the php file return to that and then continue on with the for-loop. I really feel like I'm using the wrong methods here.