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.

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 tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Using server-sent events - EventSource

Last accessed pages

  1. Node.js Move and Copy file (28419)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141747)
  3. Rectangle, Oval, Polygon - Star (3322)
  4. PHP PDO - prepare and execute (9187)
  5. jQuery Ajax - load() method (10835)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (471)
  2. CSS cursor property - Custom Cursors (78)
  3. The Mastery of Love (69)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)