<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>SSE</title>
<script type="text/javascript">
if (!!window.EventSource) {
var source = new EventSource("sse.php");
} else {
alert("Your browser does not support Server-sent events! Please upgrade it!");
}
source.addEventListener("message", function(e) {
console.log(e.data);
if(e.data){
x = document.getElementById("timer");
x.innerHTML=e.data;
console.log(e.data);
}else{
console.log(e.data);
e.close();
}
}, false);
source.addEventListener("open", function(e) {
console.log("Connection was opened.");
}, false);
source.addEventListener("error", function(e) {
console.log("Error - connection was lost."+e);
}, false);
</script>
</head>
<body>
<div id="timer"></div>
</body>
</html>
My Server Side Code
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
$lastId = 0;
while (true) {
$data =10;
if ($data) {
sendMessage($lastId, $data);
$lastId++;
$data--;
}else{
exit;
}
}
function sendMessage($id, $data) {
//echo "id: $id\n";
echo "$data\n\n";
ob_flush();
flush();
}
?>
What is wrong with my code? Please let me know.