HTML5 Server-Sent Event

Viewed 1037

I am trying to build real time app using SSE. But it doesn't work when I think I write everything in right way. Please help me with this problem. I know websockets is better than SSE but I in beginning Here is my index.html code

<!DOCTYPE html>
<html>
<head>
<title>Using SSE(Server-sent event)</title>
<meta charset="utf-8">
</head>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("getdata.php");
    source.onmessage = function(event) {  
        console.log(JSON.parse(event.data));
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

and this is getdata.php page

   <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    $pdo = new PDO("mysql:host=localhost;dbname=sse", 'root', 'secret');
    $obj = $pdo->query("select * from users");
    $arr = $obj->fetchAll();
    echo "data: ".json_encode($arr);
    flush();
   ?>

when i used

source.onerror = function(er){
   console.log(er);   
}

I got this

error { target: EventSource, isTrusted: true, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false, timeStamp: 5152.813223, cancelBubble: false, originalTarget: EventSource }

I tried comment code in html console.log(JSON.parse(event.data)); but it doesn't work too.

Please help understanding how SSE works and what is the wrong in my code?

Thanks in advance.

3 Answers
Related