To get start with EventSource
API I wrote the most scholastic example.
The problem is that I'm always getting error and I can't find any useful information about it. When I load home.html
, the JS script stops at source.onerror
; I print it into the console but analyzing the object I can't find any error type or message so I have no idea of what it's wrong. Is there an error in the code? Could be an error related to the server?
home.html
<body>
<div id="result"></div>
<script src="sse.js"></script>
</body>
sse.js
function isSseEnabled() {
return (typeof EventSource !== "undefined");
}
if (isSseEnabled()) {
var source = new EventSource('source.php');
source.onerror = function(e) {
console.log(e);
source.close();
};
source.onmessage = function (e) {
console.log(e.data);
document.getElementById('result').innerHTML += e.data.concat('<br>');
}
} else {
throw 'SSE not enabled';
}
source.php
<?php
header('Content-Type: text/event-stream');
header('Cache-control: no-cache');
$time = date('r');
echo "Time: $time";
flush();