Loading Please Wait...
HTML server-sent event allow web page to get updates from the server automatically.
HTML page does not need to check for updates, if there is any updates, the server send it to the web page automatically.
First of all, we need to check whether server-sent event is supported or not.
if(typeof(EventSource) !== "undefined"){
alert('SSE supported.');
} else {
alert('SSE not supported.');
}
To receive SSE updates from the server we need to create an object and define the server using EventSource() object.
var eventSource = new EventSource("sse_example.php");
To receive messages from server we use onmessage event listener.
eventSource.onmessage = function(event){
document.getElementById("result").innerHTML = event.data;
}
To receive SSE updates, we need to create server and a file. You can use online server or offline server like WAMP, XAMP, Visual Studio, etc.
The main thing to consider when creating server file is to set the header "content type" to "event source".
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
Set the "Content-type" header to "text/event-stream"
Set that the page should not cache data.
Get the time
Output the data (Always start with "data: ").
Flush the data back to HTML page.
<!DOCTYPE html>
<html>
<head>
<script>
if(typeof(EventSource) !== "undefined"){
var eventSource = new EventSource("sse_example.php");
eventSource.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
alert('SSE not supported.');
}
</script>
</head>
<body>
<h1>Server Updates</h1>
<p id="result"></p>
</body>
</html>
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved