Server Sent
events is the way to automatically to send request to server and get response
after regular time interval.SSEs are uses HTTP protocol i.e it does not require
special server like socket. Best use is get live notification from server. For
example if we have social networking site and we need friend request
notification or accept notification.
How to use steps
:
1. Let suppose we
are working in friends controller then in the action get_friend_request_count:
function
get_friend_request_count($user_id){
header('Content-Type:
text/event-stream');
header('Cache-Control: no-cache');
//example
query
$friend_count
=
$this->friend->find('count',array('conditions'=>array('user_id'=>$user_id)));
echo
"retry: 5000\n data: Friend count : { $friend_count}\n\n";
flush();
die;
}
2. Write a
javascript code that is available every where or in the layout:
<div id="friend_count"></div>
<script tye="text/javascript">
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource('localhost/friends/get_friend_request_count');
//modify path as correct path
source.onmessage=function(event)
{
$('#friend_count').html(event.data);
};
}
else
{
alert('Server sent event does not work with IE')
}
</script>
</script>
Comments
Post a Comment