Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Server-Sent Event

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.

like image 207
B.Nabeih Avatar asked Sep 12 '26 15:09

B.Nabeih


1 Answers

I found out it why it doesn't work. I added \n\n

echo "data: ".json_encode($arr);

so it looks like this

echo "data: ".json.encode($arr)."\n\n";

I hope it helps

like image 132
B.Nabeih Avatar answered Sep 15 '26 05:09

B.Nabeih