Search code examples
javascripthtmlserver-sent-events

how to refresh div in same position avoiding repeat line


need to refresh a div with data from server. server is sending data with Server-Sent Events.

all is working ok, but the data is shown in new lines. i need to refresh the same div in same position, not adding more lines.

This is the html page:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>

        <div id="result">Loading data. Please, wait...</div>

        <script type="text/javascript">
            if(typeof(EventSource) !== "undefined") {
                var source = new EventSource("demo_sse.php");

                source.addEventListener('message', function(e) {
                    document.getElementById("result").innerHTML += event.data + "<br>";
                }, false);

                source.addEventListener('open', function(e) {
                    // Connection was opened.
                    //alert('Connection opened');
                }, false);

                source.addEventListener('close', function(e) {
                    // Connection was opened.
                    alert('Connection closed');
                }, false);

                source.addEventListener('error', function(e) {
                    if (e.readyState == EventSource.CLOSED) {
                    // Connection was closed.
                        alert('Connection closed');
                    }
                }, false);

            } else {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
            }
        </script>
    </body>
</html>

and this is the php file:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "retry: 1000\n";
echo "data: The server time is: {$time}\n\n";
//error_log('XXXX');
flush();
?>

Solution

  • Change the line to this:

    source.addEventListener('message', function(e) {
                        document.getElementById("result").innerHTML = event.data + "<br>";
                    }, false);