How To Send Json_encode Data With Html5 Sse
Solution 1:
You need to send it in EventStream format, which in this case is just prepending it with data:
echo'data: ' . json_encode($data) . "\n\n";
Solution 2:
You can encode the $data
array like Ryan said:
echo'data: ' . json_encode($data) . "\n\n";
Then, client side, event.data
will be viewed as a string, which you can then easily parse to json using query's jQuery.parseJSON()
. so your client-side code will look something like this:
// Check if the browser supports SSEif (typeof (EventSource) !== "undefined") {
var source = newEventSource("script.php");
// Handle evetns
source.onmessage = function(event) {
// parse the data that has an object as a stringvar msg = $.parseJSON(event.data);
// Do awesome code with the values inside msg
};
} else {
alert("Sorry, your browser doesn't support this awesome feature!");
}
Solution 3:
Your script will only show output once as it needs to have some kind of a loop to keep running (conditionally of course or you'll have millions of instances running!!).
I've chopped up an implementation I wrote earlier today which demonstrates this and also added some additional javascript/jquery to help manage the streams better. The below will also work on a single threaded PHP installation like Xampp (for local development) Notes on Xampp: As the PHP script is in a loop and doesn't terminate immediately it will stop a new php or agax script from running. If you're using ajax as well to call PHP call stream_close() in the beforesend and stream_open() in the success callbacks.
The below is untested but it's mainly grabbed from working code so it should be fine.
<?//stream.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
stream();
functionstream(){
$data = array();
//collect data from database or wherever to stream to browser//example data$data[0]["name"] = 'Bob';
$data[0]["total"] = rand(0,100);
$data[0]["name"] = 'Jane';
$data[0]["total"] = rand(0,100);
//maybe there is no new data so just send one new line//this is required to check if the connection is still aliveif(!empty($data)){
echo"\n";
}else{ //Otherwise json encode the data for outputecho'data: '.json_encode($data)."\n\n";
}
flush(); //Flush the result to the browser
sleep(1); //Wait a second (or what ever you like)//If the browser is still connectedif(!connection_aborted() && connection_status()==0){
stream(); //recurse the function
}
}
?><script>var webstream = false;
functionstream_open(){
stream_close(); //Close the stream it (in case we got here weirdly)if(!!window.EventSource){ //Test compatibility
webstream = newEventSource('./stream.php');
console.log("Stream Opened"); //Log event for testing
webstream.addEventListener('message', function(e){
var data = JSON.parse(e.data); //Parse the json into an objectprocess_stream(data);
},false);
//Cleanup after navigating away (optional)
$(window).bind('beforeunload', function(){
webstream.onclose = function(){}; //delete onclose (optional)
webstream.close(); //Close the stream
});
}
}
functionstream_close(){
if(typeof(webstream)=="object"){
webstream.close();
webstream = false;
console.log("Stream Closed"); //Log event for testing
}
}
functionprocess_stream(data){
//do something with the new data from the stream, e.g. log in consoleconsole.log(data);
}
//Optional://Toggle stream on blur/focus//Good if the user opens multiple windows or Xampp?
$(window).on("blur focus", function(e) {
//get the last blur/focus event typevar prevType = $(this).data("prevType") || null;
if (prevType != e.type){
console.log(e.type); //Log event for testing (focus/blur)switch (e.type){
case"blur":
stream_close(); //Close stream on blurbreak;
case"focus":
stream_open(); //Open stream on focusbreak;
}
}
//Store the last event type to data
$(this).data("prevType", e.type);
});
// Optional:// Using idletimer plugin to close the stream in times of inactivity// https://github.com/thorst/jquery-idletimer/blob/master/src/idle-timer.js
$(document).on("idle.idleTimer", function (){
stream_close();
});
$(document).on("active.idleTimer", function (){
stream_open();
});
$(document).idleTimer({timeout:5000}); //5 second idle timer</script>
Post a Comment for "How To Send Json_encode Data With Html5 Sse"