HTML SSE API

    HTML SSE(Server-Sent Event) API allows updating the front end content from a server without refreshing or re-requesting the page.

    Server-Sent Event(SSE): One Way Messaging

    The Server-Sent Event automatically updates the web page from the server. In the background, the web-page continuously asks the server for the update. It is also known as one way messaging because the client can not send any event back to the server. All the web site such as Facebook updates, twitter updates, livestock price update, sports live score uses Server-Sent Events.

    Receive Event from the Server

    The Server-Sent Event uses EventSource interface to open the connection to the server and receive the event. To create a new event source we use the EventSource constructor.

    const evtSource = new EventSource("action.php");

    The action.php contains the server-side PHP code, that is capable of sending data updates. Every time the event source object receive an update the onmessage event occurs.

    evtSource.onmessage = function(event) {
      document.getElementById("result").innerHTML += event.data + "<br>";
    };

    Summary

    • The Server-Sent Event automatically updates the web-page from the server.
    • It is known as One way messaging because the client cannot send updates back to the server.
    • The EventSource() create a new event source to the server and receive the update.