Course Content
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
HTML SSE API
In the second section, you learned about client-side events and how you can respond to them with the help of Javascript and DOM. Then what about the server-generated events?
What are Server Sent Events?
You may already know that specific data updates in real-time, such as the stock market or financial data. Other real-time data updates include Facebook, and Twitter updates, news feeds, and live scores of your favorite soccer or baseball game.
These are possible with the events that the server sent. In this chapter, you'll find out how to capture such server-sent events on the client side and display them on the front end.
Let’s find out with a simple program how to receive the server-side client notifications.
Handling Server Sent Events on Client Side
We'll create a simple program that continuously displays updates on the current date and time. For this program to work, you must also include the server-side code.
Since PHP works closely with front-end HTML and Javascript, we choose it as the back-end programming language for this chapter. However, if you're unfamiliar with PHP, you can write the back-end code in the language of your choice, and the front-end logic stays the same.
First, the client program needs to connect to the server code file by specifying the path to the file using an instance of EventSource
class.
Then once you instantiate the EventSource
instance, it listens to the event the server triggers. Then in the following line, since the event data is in JSON format, it converts to a string. Then this string is displayed in the next line in the <div>
element with id 'result'.
Open a blank PHP file for the server-side code and name it sample_demo.php. For this tutorial, make sure you save it in the same directory as the file with the client code.
sample_demo.php
The above two lines for declaring the headers are the most important ones for this program. The first indicates that this file sends the data in the MIME text/event stream.
The second header specifies that the browser shouldn't cache the page.
The above line is self-explanatory as it sets the time zone. Next, place the code below between the time zone declaration and the closing PHP tag.
Code explanation:
- We set an infinite loop. Since this is for demonstration only, we have developed the loop while condition to true so that the code can send events after every 1 second as specified in the
sleep
method below; - Then the date output is echoed as a JSON text string;
- However, since it needs to output on the client side, we make sure that it doesn't output immediately and has to wait til the code executes to the end. This is what
flush
andob_end_flsuh
do; - The if statement ensures that when the client program exits, the loop also breaks, and thus its execution stops.
Thanks for your feedback!