Site icon i2tutorials

HTML SS Event

HTML SS Event(SSE)

 

The HTML5 server-sent event(SSE) enables a window browser to receive automatic updates and data from a server via HTTP connections.

we perform some event and send it to the server-side such as by submitting the form to the server. So such type of event which flows from web browser to web-server is called a client-side event. But if the server sent event some updates or details to the browser, then such events are called server-sent events. The window browser automatically updated from the Server.

 

Receiving events from the server:

 

The Server sent event(SSE) uses the EventSource object to receive events from the server. It provides the URI of the script which generates the events.

 

if(typeof(EventSource) !== "undefined") { 
  var source = new EventSource("ServerUpdate.php"); 
  source.onmessage = function(event) { 
   document.getElementById("output").innerHTML += event.data + "<br>"; 
  }

 

Code Explanation:

 

 

Sending events from the server:

 

To work with server-sent, we need a server that can send data updates to the web browser. For this, we need to create a file in ASP, PHP, or any dynamic language.

 

Example: ServerUpdate.php:

 

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

 

Code Explanation:

 

 

Example:

 

 <!DOCTYPE html>
<html>
<head>
 <style type="text/css">
  div{
   text-align: center;
   background-color: #98f5ff;
  }
 </style>
</head>
<body>

<h1 align="center">Dynamic Server Updates</h1>
<div id="output"></div>
<script>
if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("ServerUpdate.php");
  source.onmessage = function(event) {
   document.getElementById("output").innerHTML += event.data + "<br>";
  }
} else {
  alert("Sorry, your browser does not support the server sent updates");}
</script>
</body>
</html>

 

OUTPUT:

 

 

Note: To execute the above code on your web browser, you need a server installed on your system, and then run this on localhost. we can install any server such as MYSQL, XAMPP, etc.

 

Exit mobile version