Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Server Sent Events (SSE) with JSON and PHP

Tags:

json

html

php

I'm trying to set up a HTML5 Server Sent Event that updates a webpage with JSON data. I've checked out a ton of info sites and tutorials online but there doesn't seem to be any that are written for complete beginners (like me).

I've also checked answers to similar questions on this StackExchange but still cannot work this out.

I could only get an basic example from 'w3schools' to work, although this doesn't use JSON.

I'm hoping someone can show me how I can get HTML5 Server Sent Events to work with JSON data.

The files which I got working are as follows:

HTML

<!DOCTYPE html>
<html>
<body>

<h1>Getting server updates</h1>


<div id="result"></div>

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

</body>
</html>

PHP

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

   $time = date('r');
   echo "data: The server time is: {$time}\n\n";
   flush();
?>

An example of the type of JSON data I'd like to use with SSE is as follows:

{"employees":[
    {
        "firstName":"John", 
        "lastName":"Smith",
        "age":"25"
    },
    {
        "firstName":"Sally", 
        "lastName":"Simpson",
        "age":"24"
    },
    {
        "firstName":"Pete", 
        "lastName":"Daltry",
        "age":"30"
    }

]}

I have had some success with jQuery and the JSON file above using the following script:

<body>

<p id="team"></p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/
jquery.min.js">
</script>

<script>

$(document).ready(function(){
    $.getJSON("team.json", function(data){
        $.each(data, function(){
            $.each(this, function(key, value){
                $("#team").append(
                "First Name: " + value.firstName + "<br>" +
                "Last Name: " + value.lastName + "<br>" +
                "Age: " + value.age + "<br><br>"
            );
        });
    });
});
});

</script>

</body>

However, I cannot get SSE to work with JSON data.

Any help would be greatly appreciated.

like image 476
Mekong Avatar asked Mar 12 '16 08:03

Mekong


People also ask

What do HTML 5 server-sent events do?

A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

Is SSE better than WebSockets?

SSE is best used when it's not necessary to send data from client to server. For example, in status updates and push notification applications, the data flow is from the server to the client only. This is what SSE is designed for, so WebSocket would be overkill. It's always wise to use the best tool for the job.

What is the difference between server-sent events SSEs and WebSockets in HTML5?

Differences. Obviously, the major difference between WebSockets and Server-Sent Events is that WebSockets are bidirectional (allowing communication between the client and the server) while SSEs are mono-directional (only allowing the client to receive data from the server).

What is SSE in HTML5?

Along with HTML5, WHATWG Web Applications 1.0 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Using SSE you can push DOM events continuously from your web server to the visitor's browser.


1 Answers

As the data coming from server is in string format you can send a json string from the server. The code will be (server side code).

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

$data = array(
    'firstName'=>'Test',
    'lastName'=>'Last'
);
$str = json_encode($data);
echo "data: {$str}\n\n";
flush();

and on client side.

var source = new EventSource("events.php");
source.onmessage = function(event) {
    var jdata = JSON.parse(event.data);
    console.log(jdata);
};
like image 86
appsdevpk Avatar answered Oct 07 '22 00:10

appsdevpk