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

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>

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

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:

//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";

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.


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

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. More articles by Sue Smith
  • 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.

  • Does not work.

  • jeff_DD

    Demo is live now.

  • 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


  • 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”;

    • 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!

  • 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”;

  • 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).

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

  • 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”;

  • 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

  • Karo Castro-Wunsch

    Thanks! After the .”nn” it works 100% on safari

  • John Komar

    This is a little old to say the least but with a few tweaks it works good and a good primer on streaming content.
    The following PHP tweaks will work

    header(‘Content-Type: text/event-stream’);
    header(‘Cache-Control: no-cache’);
    $new_data = rand(0, 1000);
    echo “data: New random number: $new_datann”;

  • AmoARG69

    HI all! Thanks for the post!. Im new from Argentine, sorry for my poor English please.
    I’m programing an web interfarce to my intelli home . . So I use your idea.
    I folow your example and it runs ok. But wen I try to run a more complex php simply doesn’t works.
    For example date time refresh:

    it works if I call directly from safari, but no run if I call it from the main php page. Some ideas?

    Thanks a lot in adavance. Daniel.

  • DarnItMan

    I would like to 3rd.. or 100th, the comments here that this is yet another article that propagates the incorrect perception online, this time with EventSource (last was WebSockets): that the non-commercial community actually knows how to create a full, end-to-end, working and useful implemetation of this tech. So far all signs point me in the same direction as last year when I finally investigated Web Sockets – NOTHING outside the licensed realm has a full working example of it in action. The browsers support it, but nobody has provided a non-commercial implementation of the server side and can demonstrate it in action.

    It’s very frustrating, because if the online community was not copy-pasting the perception all over the place that this is a solved problem, someone would finally sit down and come up with a real working example.

  • DarnItMan

    And of course.. 2012 this was written.. still readily available.. does Not solve the problem.. author has dusted off their hands and wandered off ages ago.


    • pax

      check @johnkomar:disqus’s answer, that fixes it.

  • King Beauregard

    I wonder if you’ve got a couple of newlines after your closing “?>”. As such it works for you, but it’s not demonstrated as an aspect of your code (much less a necessary aspect).

  • leegee

    There is a demo. Did you read to the end?

  • Adventure

    HTML 5 SERVER-SENT EVENTS in 2017.. This article should be updated or removed.

Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress