user111671
user111671

Reputation: 431

Do server-sent events only handle strings?

I'm using SSE to stream content without the need of refreshing the webpage. Basically my main procedure is the following:

$query = "SELECT something something";
$result = $mysqli->query($query);
// ^this will return multiple rows eventually

$content= array();
while($inside= $result->fetch_assoc()){     

        array_push($content,$inside);

        }

//$content is now an array with multiple rows, all inserted corrected by debug

$final = json_encode($content);
//^ the json is encoded as supposed [{"something":"something"},{"another":...}]

echo "data: {$final}";
//^ which I then receive with javascript (or at least I want to).
flush();

The thing is that nothing is received in javascript. No errors, no console.logs, nothing at all. I've tried to work around the json in javascript but it just feels ghastly (no json there at all). Is this impossible to do? How should do it then if so? (I have tested with time() and the javascript is working completely fine dumping the data)


EDIT : JAVASCRIPT

var source=new EventSource("test.php");
    console.log("1");
    source.onmessage=function(event)
      {
            console.log("inside .onmessage !!!");
            var data = event.data;
            //data.forEach(function(each){
            //  console.log(each);
            //});
                //var data = JSON.parse(event.data);
            console.log(data);
      };

Commented parts are related to my problem. All other lines were to debug with the time() function.

Upvotes: 0

Views: 816

Answers (1)

Bergi
Bergi

Reputation: 664444

It seems that you have forgotten the stream format:

Each message is separated by a pair of newline characters.

Try

echo "data: {$final}\n\n";

Upvotes: 5

Related Questions