HTML5 SERVER-SENT EVENTS allows a web page automatically update data from a Web server.

Before a website that needs updating had to file a petition to a web server. Now a web page can be updated automatically whenever there is any change in the server data, the website will receive them without having to request them.

Thus a web page is automatically updated without user intervention, without having to refresh the page, like, a listening service, which receives information from a server without having to do anything to receive it.

Example is used:
- Pages that show automatic updates on FACEBOOK and TWITTER
- Pages that display automatically updated news (RSS FEEDS)
- Pages that display sports scores automatically.


var server=new EventSource("time.php");

They create an object-SENT EVENT SERVER, called "server", which is implemented in dynamic web page "time.php"

Example of use:

1. - First create the website will be updated automatically:

Create the page "time.htm"

<!DOCTYPE html> <html> <body> <h1>Server updates</h1> <div id="text"></div> <script> if(typeof(EventSource)!=="undefined") {   var server=new EventSource("time.php");   server.onmessage=function(event) {    document.getElementById("text") + "<br/>"; }; } else {   document.getElementById("text").innerHTML="Your browser does not support server-sent events"; } </script> </body> </html>

Explanation of file:

We verify that your browser supports this object HTML5


We built an object-SENT SERVER called "server" will be updated with information obtained from the website "time.php"

var server=new EventSource("time.php");

When the output of this website "time.php" change, then there will be an event that is collected on our website "time.htm" and update the item "text", thus showing our updated information automatically.

server.onmessage=function(event) {   document.getElementById("text") + "<br/>"; };

2. - Create the file "time.php" that generates the information to update

<?php   header('Content-Type: text/event-stream');   header('Cache-Control: no-cache');   $datetime = date('r');   echo "data: The server datetime is: {$datetime}\n";   flush(); ?>

Explanation of the previous file:

The header indicates the content type is "text / event-stream"

header('Content-Type: text/event-stream');

In the header indicates that the page is not cached

header('Cache-Control: no-cache');

We pick the date and time the web server

$datetime = date('r');

We build the message with the word "data" and the message to send.

echo "data: The server datetime is: {$datetime}\n";

We send the message to the listener service