I am displaying some real time data from a MySQL database using PHP and JavaScript. Everything works as expected and the data is displaying as I want.
However, I would now like to implement two simple buttons to achieve the following;
stop
- pause the current real time feedstart
- resume the feed from where it was paused
I can get the stop
button to work by using the EventSource close()
function. I'm not so sure about how to resume from where I left off though. I think I may need to include the Last-Event-ID
as described here.
My code so far is;
PHP
<?php
session_start();
include 'conn.php'; // database connection
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Access-Control-Allow-Origin: *");
$query = "SELECT TimeStamp, CardNo, SerialNo FROM transactions ORDER BY TimeStamp DESC LIMIT 1";
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()) {
echo "retry: 100\n\n";
if ($_SESSION["lastSerialNo"] != $row["SerialNo"]) {
$_SESSION["lastSerialNo"] = $row["SerialNo"];
echo "data: ".$row['SerialNo']. ' ' .$row['TimeStamp']. "\n\n";
flush();
}
else {
// do nothing
}
}
JS & HTML
<script type="text/javascript">
var source = new EventSource("data.php");
window.onload = function() {
source.onmessage = function(event){
document.getElementById("result").innerHTML += "Data : " + event.data + "<br>";
};
};
function stop() {
source.close(); // this successfully stops the feed
};
function start() {
// how to resume the feed?
};
</script>
<button id="stop" onclick="stop()"> stop</button>
<button id="start" onclick="start()"> start</button>
Any help is appreciated.