Denis Potschien February 19th, 2013

HTML5 Server-Sent-Events: How To React On Server Requests With JavaScript

You certainly know the XMLHttpRequest object, with which it is possible to communicate with a web server from inside an HTML document and have it updated without the need for reloading the page. Now, with the newly introduced server sent event, part of HTML5, we can even react to requests from the server side without the need for a reload. This way we can keep page contents simultaneously updated. This proves useful in several cases, e. g. regarding your stock of products, that is probable to change every second.

Server Sent Events: Define Events And React To Them

To start using a server sent event, you will want to define a source. This can be a PHP file caring for server-side output and serving events to be reacted to:
var quelle = new EventSource("demo.php");
Via the event handler onmessage or the method addEventListener() we add a function that is going to be called every time the content of the source changes (in our example: demo.php):
quelle.onmessage = demo;
If possible you should always prefer the DOM standard addEventListener():
quelle.addEventListener("ping", demo, false);
Using addEventListener() carries the advantage, that you can add a name for the event (here ping) to the function. This way we can make the source react to different events. The function needs to have information on what kind of reaction shall be initiated. The simplest reaction would be to just output the source content:
function demo(e) {
  document.getElementById("demo-output").firstChild.nodeValue =;
Using .data we can access the content of the event source. Instead of only outputting the content, a lot more complex functions are thinkable.

Server Sent Events: Presets for the Event Source

The event source must comply with certain standards. Foremost it is necessary to care for the correct content type. In our PHP we would output it like this:
header("Content-Type: text/event-stream");
Second the content needs to be in UTF-8 format. As we have named the event we need to add array identifiers also:
event: ping
data: This is the output text.
The event contains the event name we attached to the addEventListener(), while data contains the string we want to output. If more than one event is defined, each event is separated with two line-breaks from its predecessor. If you did not listen to what I advised you to do, and instead used the handler onmessage, you are not able to react to more than one event. Server sent events are supported in Chrome from version 9, Firefox 6+, Safari 5+ and Opera 11+. Our best friend Internet Exploder is not on the list, as almost always... (dpe)

Denis Potschien

Denis works as a freelance web designer since 2005.


  1. Pingback: Tweet parade (no.08 Feb 2013) | gonzoblog
  2. Pingback: How to Build Websites » HTML5 Server-Sent Events

Leave a Reply

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