Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server Sent Events : Not working

I am using HTML5 Server-Sent Events.

Actually I need to show notification (new record enter and which are unread) that's when any new record is insert in database (php/mysql).

So for testing purpose I just tried with count of total row. But I am getting this error message in my local-host:

Firefox can't establish a connection to the server at http://localhost/project/folder/servevent/demo_sse.php.

The line is:

var source = new EventSource("demo_sse.php");

I have tried this:

index.php

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

demo_sse.php

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

$db = mysql_connect("localhost", "root", ""); // your host, user, password
  if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("testdatase"); // database name
  if(!$select_db) { echo mysql_error(); }

$time = " SELECT count( id ) AS ct FROM `product` ";
$result = mysql_query($time);
$resa = mysql_fetch_assoc($result);
echo $resa['ct'];
flush();
?> 

Please let me know what going wrong.

I know for notification we can use Ajax with some interval time, but I don't want such thing. As I have N number of records and which may slow my resources.

like image 272
user3209031 Avatar asked Mar 19 '23 20:03

user3209031


1 Answers

According to this,

There are several 'rules' that need to be met, and yours is lacking at this point:

  • Output the data to send (Always start with "data: ")

It is somehow like:

echo "data: {$resa['ct']}\n\n"; 
like image 106
asubanovsky Avatar answered Mar 28 '23 00:03

asubanovsky