Server Sent Events: Not Working

I am using HTML5 server related events .

Actually I need to show a notification (new record entry and which are unread) when every new record is inserted into the database (php / mysql).

So, for testing purposes, I just tried counting the total string. But I am getting this error message on my localhost:

Firefox cannot connect to the server at http: // localhost /project/folder/servevent/demo_sse.php.

Line:

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

      

I've 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 goes wrong.

I know we can use Ajax at some interval for notification, but I don't want this kind of thing. Since I have N number of entries and that might slow down my resources.

+3


source to share


3 answers


According to this ,

There are several "rules" that need to be followed, and at the moment you are missing:

  • Print data to send (always start with "data:")


It's something like:

echo "data: {$resa['ct']}\n\n"; 

      

+3


source


Setting the header text/event-stream

worked for me:



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

// Rest of PHP code

      

+1


source


Modify the following code snippet as per your requirement.

<?php

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

// infinite loop
while (1) {
    // output the current timestamp; REPLACE WITH YOUR FUNCTIONALITY
    $time = date('r');
    echo "data: Server time: {$time}\n\n"; // 2 new line characters

    ob_end_flush();
    flush();
    sleep(2); // wait for 2 seconds
}

?>

      

I've tested this piece of code myself; it works for me. If you have any questions, please let me know.

0


source







All Articles