Hello, I have javascript code that listens for PHP code through Server-Sent Events, it works well, the response is sent from the server through the loop, and when the loop completes the Server-Sent events, it stops, however, for a few seconds after listening to the script again . how can I end Server-Sent Events when the server side loop ends too? Thanks.
JS:
var sse=new EventSource("data.php"); sse.onmessage=function(event){ document.getElementById("map").innerHTML+=event.data; };
PHP:
<?php header('Content-Type: text/event-stream'); //indicates that server is aware of server sent events header('Cache-Control: no-cache');//disable caching of response $coordinates = [ [ "20:11", 33.5731235, -7.6433045 ], [ "20:11", 33.5731054, -7.6432876 ], [ "20:11", 33.5731644, -7.6433304 ] ]; foreach($coordinates as $c){ echo "data: ".json_encode($c)."\n\n"; ob_get_flush(); flush(); sleep(1); }
source share