javascript - Server Side Events & Historical Data -
i using php , mysql in order display live data on webpage, refreshing every 1 second. working expected although implement 1 new feature.
currently on $( document ).ready() start live data feed retrieving , displaying single rows of data transactions table. can start/stop feed. far.
i display live data and have start the last 100 transactions. example, when user opens webpage see past 100 transactions, then live feed start afterwards (101, 102, 103, etc..).
currently when page loaded live feed starts @ whatever transaction returned sql query. whereas need start @ point minus 100
the past 100 transactions -100 serialno unique, auto increment key in database.
everything working regarding live feed, including start/stop buttons. feel issue due query, limit 1 part. have tried changing limit 100 when webpage shows 100 records every 1 second.
i have 2 files, data.php , index.html. have included code both below.
data.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, serialno transactions order timestamp desc limit 1"; $stmt = $conn->prepare($query); $stmt->execute(); $result = $stmt->get_result(); while($row = $result->fetch_assoc()) { //send request every x seconds echo "retry: 1000\n\n"; echo "id: " .$row["serialno"]. "\n\n"; if ($_session["lastserialno"] != $row["serialno"]) { //store new "last" serial no in session $_session["lastserialno"] = $row["serialno"]; //...send data client echo "data: ".$row['serialno']. ' ' .$row['timestamp']. "\n\n"; flush(); } else { // nothing } } index.html
<script type="text/javascript"> $("document").ready(function() { // set default stopped flag false var is_stopped = false; var source = new eventsource("data.php"); var offline; source.onmessage = function(event) { if (is_stopped) { // data sent data.php offline = event.data; // put storage localstorage.setitem(event.lasteventid, offline); // retrieve storage offline = localstorage.getitem("offline"); } if (!is_stopped) { document.getelementbyid("result").innerhtml += "new transaction: " + event.data + "<br>"; } }; $("document").ready(function() { $("#start").click(function() { // set stopped flag false is_stopped = false; // loop through localstorage (var = 0; < localstorage.length; i++) { document.getelementbyid("result").innerhtml += "new transaction: " + localstorage.getitem(localstorage.key(i)) + " *<br>"; } // clear local storage localstorage.clear(); }); $("#stop").click(function() { // set stopped flag true is_stopped = true; }); }); }); //end dom ready </script> <div id="result"><!--server response here--></div> <button id="stop"> stop</button> <button id="start"> start</button> any appreciated.
Comments
Post a Comment