Search code examples
javascriptphpjqueryserver-sent-events

document.getElementById vs jQuery $html() to receive Server-sent Event Data


I'm testing to receive data with SSE

This is my stream.php file:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: test\n\n";
flush();
?>

To receive data I use:

var source=new EventSource("stream.php");
    source.onmessage=function(e)
    {
      //document.getElementById("result").innerHTML+=e.data + "<br/>";
        $("#result").html(e.data);
    };

When I use document.getElementById("result"), it show the data repeatedly. But when I use $("#result").html(e.data), it doesn't. Why ?


Solution

  • .innerHTML += adds to the already exsisting HTML, note the +=, while jQuery's html() method overwrites the HTML every time.

    jQuery has several other methods that adds to the existing markup, like append().