Using PHP and JavaScript I am trying to add a button to my website that will 'resume' a live feed of data. I can successfully 'stop' the feed, I'm just struggling to start it again.
When I stop the feed, I am saving the the lastEventId
coming from the server. When I click the start button I re-use this value and send an AJAX request to the server. This works and I am able to retrieve the lastEventId
.
I need some help starting the feed again from where it was stopped.
My JS code;
<script type="text/javascript">
$("document").ready(function(){
var lastSerial;
var source = new EventSource("data.php");
source.onmessage = function(event) {
lastSerial = event.lastEventId;
document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
console.log(event.lastEventId); // returns the `lastEventId`
};
$("#start").click(function(){
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: lastSerial},
success: function(data){
// need to start the feed again here from where it left off, based on the returned `lastSerial` value
console.log(lastSerial) // returns an INT as expected
}
});
});
$("#stop").click(function(){
source.close();
});
});//end dom ready
</script>
<div id="result"><!--live feed here--></div>
<button id="stop"> stop</button>
<button id="start"> start</button>
My data.php (simplified);
if(isset($_POST['lastSerial'])) {
// SELECT TimeStamp, SerialNo ... WHERE SerialNo >= 'lastSerial' ...
// fetch results
// echo "data: " .$row["SerialNo"]. "
";
}
So as things stand, I can successfully stop the feed. When I click start the lastSerial
is logged to the console.
Any advice is appreciated.