Javascript Course

With SSE (Server-Sent Events) the web page can automatically receive data from server without requiring any sending requests.

Receiving events from the server

Server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client.
To receive server-sent event notifications in JavaScript, create an object of the EventSource interface, specifying the URL of the page that sends the messages.

var evsource = new EventSource('sse_file.php');

If the script is hosted on a different domain, define the EventSource with the URI address of the script, and a second argument with an object with the withCredentials property set to true (default is false).
var evsource = new EventSource('//', {withCredentials: true});

Once you've instantiated an event source object, you can begin listening for messages from the server by listening for the message event:
var evsource = new EventSource('sse_file.php');
evsource.addEventListener('message', (ev)=>{
 //getting data from event (ev)
 let data =;

Each message event contains these properties:

Sending event message from the server

The server-side script that sends events needs to respond using the Content-Type: text/event-stream.
Each event 'message' is sent as a block of text with one or more lines, terminated by a pair of newlines.
Syntax (in PHP):
header('Content-Type: text/event-stream');
echo "data:$data\n";
echo "retry:$retry\n";
echo "id=$id \n\n";

The message string must end with two new line characters '\n\n'.
If the string message starts with a colon (:), it is considered a comment, and is ignored.
echo ': Text ignored \n\n';
If a line doesn't contain a colon, the entire line is treated as the field name with an empty value string.

Example server sent events

Here is a simple example that helpls to understand how the server-sent events work with the EventSource object.
- This example displays in a HTML element the time (hour:minutes:seconds) from server side
<h3>Example server sent events with EventSource</h3>
<h4>Server-Time: <span id='ss_time'></span></h4>

var ss_time = document.getElementById('ss_time');

//if the browser supports EventSource
 //defines an EventSource object to receive data from sse_ex.php file
 var evsource = new EventSource('javascript/sse_ex.php');

 //detects when it is received message with data from server
 evsource.addEventListener('message', (ev)=>{
 let id = ev.lastEventId; //if you need the event message id

 //gets and adds data in #ss_time
 let data =;
 ss_time.innerHTML = data;
else ss_time.innerHTML ='No server-sent events support.';
The server-side event stream syntax is simple. First, set the 'Content-Type' header to 'text/event-stream'. Now you can start sending event streams with 'echo' (in PHP).
- The sse_ex.php file contains this code:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); //to prevent caching of event data
header('Access-Control-Allow-Origin: *'); //allows stream access from current domain only

$time = date('h:i:s');
$id = time(); //to set id with current timestamp

//outputs message with a time interval of 1 second (1000 milliseconds
echo "data:$time\n";
echo "retry:1000\n";
echo "id=$id \n\n";

//sends output data to the browser

Closing event streams

By default, if the connection between the client and server closes, the connection is reset.
To terminate the connection from the client side, apply the close() method.
var evsource = new EventSource('sse_file.php');
//rest of code..

if(some_condition) evsource.close();

To terminate a stream from the server, respond with a non "text/event-stream" Content-Type, or return an HTTP status other than 200 OK (e.g. 404 Not Found).
header('HTTP/1.0 404 Not Found');
- It will prevent the browser from re-establishing the connection.

Using custom name for server sent event

The 'message' is the default event name for server-sent events, but it can be specified a custom name on the server-side, by adding the event field in the block of text that is sent to the browser.
Syntax (in PHP):
echo 'event:event_name\n';
echo "data:$data\n";
echo "retry:$retry\n";
echo "id=$id \n\n";

Then, on the client side the JS script can listen for the specified event name.
var evsource = new EventSource('sse_file.php');
evsource.addEventListener('event_name', (ev)=>{
 //getting data from event (ev)
 let data =;
- This code will be called automatically whenever the server sends a message with the event field set to "event_name".

Daily Test with Code Example

What attribute makes a radio button or checkbox input selected?
checked="checked" selected="selected" disabled="disabled"
<input type="checkbox" name="a_name" value="value" checked="checked" />
What CSS value scales the background image to the largest size contained within the element?
repeat-x contain linear-gradient
#id {
What operator is used to determine the rest of the division of two numbers?
% * /
var rest8_7 = 8 % 7;
Indicate the PHP function that rounds a number up to the next highest integer.
floor() ceil() abs()
$nr = ceil(3.5);
echo $nr;        // 4
Using server-sent events - EventSource

Last accessed pages

  1. TV-Screen shape with CSS (2550)
  2. $_GET, $_POST and $_REQUEST Variables (29917)
  3. Send Email with Nodemailer (2076)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (109107)
  5. Using the Bone Tool (3385)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (62)
  2. JavaScript Course - Free lessons (43)
  3. Read Excel file data in PHP - PhpExcelReader (43)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (38)
  5. HTML Course - Free Lessons (37)