Reading list Switch to dark mode

    Server-Sent Events in JavaScript

    Updated 2 January 2020

    In this blog we will learn how we can use the Server-Send Events in JS.

    The Server-Sent Event is an EventSource Class , which keeps the server connection connected and receive the server response continuously.

    We can use this when we have to load the large data at once.

    Now, we will see how we can create an object of the Server-Sent Event class on client end.

            <script>
                var source = new EventSource("example.php");
                source.onmessage = function(event) {
                    var details = JSON.parse(event.data);
                    document.getElementById("show_data").innerHTML += details['name'] + "<br>";
                };
            </script>

    Here, first we create an object of EventSource class.

    Start your headless eCommerce
    now.
    Find out More

    Than, we call the onmessage function of EventSource Class.

    Whenever server sent the response then onmessage function calls automatically by the Server-Sent Event and display the data in the selected element.

    Now, we will look into the server end code example.

    <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    
    $details = array();
    $details['name'] = "john doe";
    echo "data: " . json_encode($details) . "\n\n";
    flush();
    ?>

    You have to defined the below header only than it will worked.

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

    Output

    output-1

    Complete Code

    <html>
        <head>
            <title>Server-Sent Events</title>
            <script>
                var source = new EventSource("example.php");
                source.onmessage = function(event) {
                    var details = JSON.parse(event.data);
                    document.getElementById("show_data").innerHTML += details['name'] + "<br>";
                };
            </script>
        </head>
        <body>
          <div id="show_data"></div> 
        </body>
    </html>

    In case you have any Query then feel free to ask in the comment section below. I hope It will help you. Thanks

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home