Pushing Updates to the Web Page with HTML5 Server-Sent Events

Mar 13, 2012
HTML5 JavaScript
197 Shares
By

The HTML5 Server-Sent event model allows you to push realtime data updates from the server to the browser.

In this tutorial we will work through the process, with the EventSource object handling received data and writing it to the page. We will use HTML5 and JavaScript at client side, with PHP at server side.

With existing models such as AJAX, the code in a Web page would continually ask the server to supply new data, but the onus was on the client to request the information. With Server-Sent requests, you can stream data from your server, with updates pushed from there without the code at client side having to keep requesting it. Once your page initiates the Server-Sent event, the server script can continue sending updates. Your JavaScript code can write this new data into the page whenever it receives it.

Create an HTML5 Page

Create your HTML5 page as follows:

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

Add an Element to Display the Server-Sent Data

We will display the data received from the server in a dedicated page element, so add the following in the body section of your page:

<div id="serverData">Here is where the server sent data will appear</div>

You can put any content you like in your element, as long as it has an ID attribute so that you can identify it in your script. The placeholder text should only appear when the page first loads, but will disappear when the script runs.

Add a Script to the Page

Because we want the function to continue receiving and handling updates, we add the script section in the body of the page. Of course your own pages may execute functions on user interaction, but for the purposes of this demonstration add the following script at the end of your page, before the closing body tag:

<script type="text/javascript">
//functions here
</script>

The script will execute when the browser renders the page, so the Server-Sent events will be initiated straight away. Next add the JavaScript code inside this script section:

//check for browser support
if(typeof(EventSource)!=="undefined") {
	//create an object, passing it the name and location of the server side script
	var eSource = new EventSource("send_sse.php");
	//detect message receipt
	eSource.onmessage = function(event) {
		//write the received data to the page
		document.getElementById("serverData").innerHTML = event.data;
	};
}
else {
	document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}

The script first checks that the browser supports the EventSource model. If it doesn’t, an error message is written to the server data page element instead. If the browser does support the function, the Server-Sent process begins. First, the script creates an object of the EventSource class, passing it the URL of the server side script that will be providing the streamed data updates. Then the script sets up an event listener function to execute when the EventSource object receives an update from the server. When this happens, the script simply gets a reference to the update page element and writes the new data to it.

Create a Server Side Script

We now need to create the server side PHP script to send updates to the page. Create a new file and save it “send_sse.php” or another name of your choice, as long as you amend the JavaScript EventSource code above to reflect the correct name and location. Enter the following outline in your PHP file:

<?php
//streaming code
?>

Begin your PHP script by setting the headers as follows:

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

This code sets the script up to stream data, preventing caching issues. Add the following inside the script, before the closing PHP tag:

//generate random number for demonstration
$new_data = rand(0, 1000);
//echo the new number
echo "data: New random number: $new_data";
flush();

For the purposes of demonstrating Server-Sent events, we are simply generating a new random number each time the script sends an update. The code first stores a new random number between zero and one thousand as a variable. Then it echoes the new data along with some text, after the text “data: ” which you must include for your script to function correctly. Finally the script flushes the output, sending it to the browser.

Upload and Test

You will need to run these scripts on a server to see them functioning correctly. Upload your HTML page and PHP script to the same directory. Browse to the page and watch the updates appear one after another.

Conclusion

In this tutorial we have carried out the basics of using Server-Sent events with HTML5, JavaScript and PHP. In our example server side script we simply generated random numbers, but in your own projects you can carry out other server side processes such as fetching data from different sources, sending fresh information to your users without their browser having to request these updates each time.

Check out this tutorial in action here: Pushing Updates to the Web Page Demo

Author: Sue Smith
Sue Smith works as a Web/ software developer and technical writer based in the UK: see benormal.info for details. Sue has written for various clients including Smashing Magazine and Mobiletuts+. She also does a little Android development and some comedy writing.
  • http://www.paulund.co.uk/ Paul

    Hi

    Nice tutorial I didn’t know about this until now. Can see how it will be useful. Is this what something like the facebook stream would use?

  • jerry

    +1 on even a basic demo, hard to grasp concept without one.

  • http://twitter.com/TheDayvi Dayvi A

    Does not work.

  • jeff_DD

    Demo is live now.

  • http://www.socialdon.com/ Social Media Statistics

    Your tips can’t make any difference but it helpful for me in some instance. Great help.

  • Abdel Hady

    Does EventSource object work with all common browsers

  • Subbu8016

    hello

  • AnAnon

    It does not work. The reason being that the line echo “data: New random number: $new_data”; is supposed to be echo “data: New random number: ” . $new_data. “nn”;

    • Saura

      Yes, you need to terminate a message using “nn”.
      Better option is to use PHP_EOL for generating the correct “End of Line”

  • Lolmewn

    Didn’t work for me until I added ob_flush();

  • Rajajowaz

    it works for me by this following code
    header(‘Content-Type: text/event-stream’);
    header(‘Cache-Control: no-cache’);
    $new_data = rand(0, 1000);
    echo “data: New random number: $new_datann”;
    ob_flush();

    • Pramod Prakash

      Your awesome!!!

    • Pramod Prakash

      But just another doubt. will this keep refreshin my webpage as a whole or not, coz that might make it irritating for the user if you know what i mean!

  • http://pulse.yahoo.com/_3QBMYPCCPWL5IDWF55BTBVWSAE UPLB-2008-3****

    The demo somewhat works – in Chrome’s Dev tools – I can see that there’s a network connection to the PHP file after every few seconds – but there’s no content in the response body!

  • mike

    PHP 101, double quotes will resolve $var… echo ” this is: $value”; is the same as echo ‘this is: ‘ . $value;

  • luca

    It works, but just a question.
    How can i control the time of refresh?
    The script run every 5 second…. can i chenge it?

    • Prasad Honavar

      echo “retry: 5000ndata: {$newdata}nn”;

  • http://www.facebook.com/balavishnu1993 Bala Vishnu

    Ur tutorial is great sir…It worked perfectly for me in localhost and in server…but when i converted tis page into an android app(using phonegap integration in DW5.5), in my mobile the error which we have printed is thrown, at the same time it works perfect in a browser in my android mobile…I think there is no permission for the app to access internet…Please help me…

  • DonW

    Is there an explanation as to why this does not work with the Chrome browser?

    I am using Chrome version 24.0.1312.2 dev-m

  • Amit Patel

    Which browsers supports CORS with SSE?

  • MIke

    It’s really horrible when you make a tutorial that is the #1 google result, and it isn’t even correct.

    As stated in the comments, the echo line needs to be terminated in a couple of newlines. How about updating the code listing for future readers?

    Second, for those asking about the refresh interval, this code above, as written, does not demonstrate EventSource the way its supposed to work. The whole point of EventSource and text/event-stream mime is that the server side should maintain the connection, this means the php script can’t immediately exit like it does in the code above. The 3 second refresh you are seeing is EventSource reconnecting after it realizes the server disconnected. The PHP code should be wrapped in a while loop and a sleep or usleep should be added in the loop to pace the streaming data. I wrapped it in a while($x++ < 200). This will send 200 numbers then drop the connection. The client side will reestablish. Note that you may run into php execution time limits depending on your sleep value (default on many systems is 30 seconds or so).

  • http://www.facebook.com/massimo.fabrizio1 Massimo Fabrizio

    The script run every 5 second…. can i chenge it?

  • http://www.kizi2.com/ kizi 2

    thanks author. This information is need. it very useful for me.

  • Anas

    Apart from the nn issue in the php output, everthing else works perfectly… now I need to dig in to see how to change the interval.

  • Pramod Prakash

    Thanx author!!! your damn cool!!

  • Sam

    Is there a way to pass a variable via the URL of the PHP, the html page will then display the latest variable that was passed. for example:

    • Sam

      For example:
      // $new_data = rand(0, 1000);
      // echo “data: New random number: ” . $new_data. “nn”;
      echo “data: New random number: ” . $_GET[“color”] . “nn”;
      ob_flush();

  • Me

    there’s a lot of good tutorials about sse but none of them have shown a good example (server side script).

    thanks for your effort but i sadly think it’s worthless