服务器端事件和Ajax请求

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.

Instead of doing source.close() use a flag to determine whether the feed has been stopped.

var is_stopped = false;

[...]

$("#stop").click(function(){
    is_stopped = true;
});

Then,

source.onmessage = function(event) {
    /** If it is NOT stopped. **/
    if (!is_stopped) {
        lastSerial = event.lastEventId;
        document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
        console.log(event.lastEventId); // returns the `lastEventId`
    }
};

Or,

source.onmessage = function(event) {
    /** If it IS stopped. **/
    if (is_stopped)
        return false;

    lastSerial = event.lastEventId;
    document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
    console.log(event.lastEventId); // returns the `lastEventId`
};

That way you aren't actually killing the event, so when you want to restart the feed you just set is_stopped to false and everything resumes as before.