Question

I have a javascript that fires an EventSource for the page "checkMessages.php". That page returns data only if there is something new entered in the database.

The problem here lies with Mozilla Firefox, because it does not update the SSE content whenever there is any change in the database. I checked the same with Google Chrome, and everything works absolutely fine.

Moreover, I checked an HTML5 SSE demo from http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_sse in Firefox, and it works. What's wrong with this code then?

index.php:

<script type="text/javascript">
if(typeof(EventSource)!="undefined")
{  
  var source=new EventSource("checkMessages.php");
  source.onmessage=function(event)
  {
        $("#new_message").html("Inbox"+event.data);
  }
}
else
{ 
        $("#new_message").html("HTML5 not supported");
}

</script>

<div id="new_message_container">
    <span id="new_message" onclick="readInbox($userid)">
        Inbox
    </span>
</div>

checkMessages.php:

<?php
session_start();
require_once 'myfunctions.php';
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$userid=studentidOf($_SESSION['user']);
$query="Select msgby from messages where msgfor='$userid'";
$result=queryMysql($query);
$k=mysql_num_rows($result);

if($k>0)
    echo "data:($k)";

flush();
?>
Was it helpful?

Solution

The EventSource specification describes the following:

The stream must then be parsed by reading everything line by line, with a U+000D U+000A (CRLF) character pair, a single U+000A (LF) character not preceded by a U+000D (CR) character, and a single U+000D (CR) character not followed by a U+000A (LF) character being the ways in which a line can end.

and

Lines must be processed, in the order they are received, as follows:

  • If the line is empty (a blank line): dispatch the event

This means that if the event data is not followed by a blank line, the event is not dispatched.

The fix for the PHP code above is to make sure the data line is correctly terminated and a new empty line is introduced:

if($k>0)
    echo "data:($k)\n\n";

OTHER TIPS

I encountered the same problem and adding 1 header seems to fix the Firefox problem.

header('Connection: keep-alive');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top