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.

Syntax:
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).
Syntax:
var evsource = new EventSource('//api.example.com/sse_file.php', {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 = ev.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>

<script>
var ss_time = document.getElementById('ss_time');

//if the browser supports EventSource
if(window.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 = ev.data;
 ss_time.innerHTML = data;
 });
}
else ss_time.innerHTML ='No server-sent events support.';
</script>
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:
<?php
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
ob_flush();
flush();

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');
exit();
- 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 = ev.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

HTML
CSS
JavaScript
PHP-MySQL
Which attribute indicates that an input field must be filled out before submitting?
required="required" autofocus="autofocus" placeholder="text"
<input type="text" name="name1" required="required" />
Which CSS method increases or decreases the size of the HTML element (including its content)?
translate() scale() skew()
#some_id:hover {
  transform: scale(2, 1.5);
  -ms-transform: scale(2, 1.5);    /* IE 9 */
  -moz-transform: scale(2, 1.5);   /* Firefox */
}
Click on the Date object method that returns the day of the month.
setDate() getMonth() getDate()
var rightnow = new Date();
var day = rightnow.getDate();
alert(day);
Which function is used to upload a file on server?
is_file() move_uploaded_file() fopen()
if(move_uploaded_file($_FILES["field_name"]["tmp_name"], "dir/file_name")) {
  echo "The file succesfully uploaded";
}
Using server-sent events - EventSource

Last accessed pages

  1. Get the value of the selected /checked checkboxes in a form (38934)
  2. Create ZIP file archive with PHP (1431)
  3. Get and Modify content of an Iframe (14290)
  4. Ajax MySQL CRUD Query Builder with Pagination (218)
  5. Script Users Register, Login, Online (16470)

Popular pages this month

  1. Insert, Select and Update NULL value in MySQL (410)
  2. Read Excel file data in PHP - PhpExcelReader (329)
  3. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (254)
  4. PHP getElementById and getElementsByTagName (205)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (198)