Wednesday, April 18, 2012

Twitter like Real Time Wall Update Using Pusher API and jQuery

4/18/2012

If you have ever dreamt of showing real time data on your website then this tutorial is for you. In this tutorial I will show you how to show real time updates and data on you web pages. Here I will use Pusher API to create a two way communication between the client and server. The Pusher API uses websockets for the two way communication and its free for starting your development.
Here I have created a Twitter/Facebook style real time updating wall script that will display the status updates of the users in real time. I have used the excellent twitter wall layout by Srinivas Tamada from 9lessons. See the live demo.


For the exact effect, open the demo page in two browsers and check them simultaneously.
Live Demo Download Script

1. The HTML Layout

We have included the jQuery library, then Pusher library and our javascript and style.css.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<link href="style.css" type="text/css" rel="stylesheet">
<script src="http://js.pusher.com/1.11/pusher.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type="text/javascript" src="script.js"></script> 
</head> 
 
<body> 
 <div id='container'>
  <div id="header">
   <textarea cols="80" rows="2" class="t_area" id="status"></textarea>
   <br />
   <input type="text" name="username" id="username" class="t_box" />
   <input type="button" class="btn" id="update_btn" value="Update" />
  </div>
  <div class='right'>
   <h4>This tutorial shows you how to create Twitter/Facebook like real time wall updates using Pusher API and jQuery. This tutorial <a href='http://www.webspeaks.in/2012/04/twitter-like-real-time-wall-update.html' style='color:#cc0000'>click here</a></h4> 
  </div> 
  <div id="panel-frame"> 
   <div class="panel"> 
    <div class="head"> 
     <a href="#" class="close">Close</a> 
    </div> 
    <div class="data" style="padding:20px"></div> 
   </div> 
  </div> 

  <div class="left"> 
   <div class="block" id="1">Test message</div>
  </div>
 </div> 
</body> 
</html>

2. Initializing Pusher Object

var pusher = new Pusher('352cb21a5ef3e5d8e0fe'); //This is your app key

//channel is the medium for the communication
var ws_channel = pusher.subscribe('ws_channel'); //you can create any channel

3. Sending data to server

$('#update_btn').click(function(){
 var status = jQuery.trim(jQuery('#status').val()); //get the status
 var username = jQuery.trim(jQuery('#username').val()); get the username
 if(status == ''){
  alert('Please enter your message.');
  jQuery('#status').focus();
  return false;
 }
 if(username == ''){
  alert('Please enter your username.');
  jQuery('#username').focus();
  return false;
 }

 //make ajax call to the server
 $.ajax({
  type : "POST",
  url : 'send_update.php',
  dataType : "json",
  data: { update : status, username : username },
  beforeSend: function(){
   jQuery('#update_btn').val('Updating...');
  },
  success : function(msg) {
   if( msg.success ) {
    //do nothing
   } else {
    //alert(msg.errormsg);
   }
   jQuery('#update_btn').val('Update');
  },
  error: function(msg) {
  }
 });
});

4. Create send_update.php

Note that we have created 'new_update' event in this file. This event is fired when the status update takes place and it can be used in the JavaScript code on client side like any other event.
<?php
//include the pusher publisher library
include_once 'Pusher.php';

$pusher = new Pusher(
 '352cb21a5ef3e5d8e0fe', //APP KEY
 '88cbaa5abd8c8d8d7fa9', //APP SECRET
 '18728' //APP ID
);

//get the message posted by our ajax call
$update = $_POST['update'];
$username = $_POST['username'];

//trim it
$update = trim($update);
$username = trim($username);

$message = "{$update} <span class='username'>@{$username}</span> <span class='time'> ".date('Y-m-d H:i:s').'</time>';

//trigger the 'new_update' event in our channel, 'ws_channel'
$pusher->trigger(
 'ws_channel', //the channel
 'new_update', //the event
 array('update' => $message) //the data to send
);

//to be returned to our ajax call
echo json_encode(array(
 'update' => $message,
 'success' => true
));
exit();
?>

5. Bind the event in client side JavaScript

//new_update was triggered in send_update.php
//bind our update code with new_update event
ws_channel.bind('new_update', function(data) {
 update_wall(data);
});

//this function performs the update
function update_wall(data) {
 var parent = $('div.left');
 var len = parent.find('div.block').length;
 var htm = '<div class="block" id="'+len+'">'+ data.update +'</div>';
 parent.prepend(htm);
 jQuery('#status').val('');
}

6. Show the twitter style detail window

This code has been borrowed from Srinivas Tamada at 9lessons.
$('.block').live('click', function(){
 var id= $(this).attr('id');
 var text = $(this).html();
 var data_id= $(".data").html();
 var panel= $('.panel');
 var panel_width=$('.panel').css('left');
 if(data_id==id){
  panel.animate({left: parseInt(panel.css('left'),0) == 0 ? +panel.outerWidth() : 0});
 }else{
  if(panel_width=='341px'){

  }else{
   panel.animate({left: parseInt(panel.css('left'),0) == 0 ? +panel.outerWidth() : 0});
  }
 }
 $('.data').html(text);
 return false;
});
$('.close').click(function(){
 var panel= $('.panel');
 panel.animate({left: parseInt(panel.css('left'),0) == 0 ? +panel.outerWidth() : 0});
 return false;
});

7. Complete JavaScript Code

var pusher = new Pusher('352cb21a5ef3e5d8e0fe');
var ws_channel = pusher.subscribe('ws_channel'); //join the ws_channel channel

$(document).ready(function() {
 $('.block').live('click', function(){
  var id= $(this).attr('id');
  var text = $(this).html();
  var data_id= $(".data").html();
  var panel= $('.panel');
  var panel_width=$('.panel').css('left');
  if(data_id==id){
   panel.animate({left: parseInt(panel.css('left'),0) == 0 ? +panel.outerWidth() : 0});
  }else{
   if(panel_width=='341px'){

   }else{
    panel.animate({left: parseInt(panel.css('left'),0) == 0 ? +panel.outerWidth() : 0});
   }
  }
  $('.data').html(text);
  return false;
 });
 $('.close').click(function(){
  var panel= $('.panel');
  panel.animate({left: parseInt(panel.css('left'),0) == 0 ? +panel.outerWidth() : 0});
  return false;
 });

 function update_wall(data) {
  var parent = $('div.left');
  var len = parent.find('div.block').length;
  var htm = '<div class="block" id="'+len+'">'+ data.update +'</div>';
  parent.prepend(htm);
  jQuery('#status').val('');
 }

 ws_channel.bind('new_update', function(data) {
  update_wall(data);
 });

 $('#update_btn').click(function(){
  var status = jQuery.trim(jQuery('#status').val());
  var username = jQuery.trim(jQuery('#username').val());
  if(status == ''){
   alert('Please enter your message.');
   jQuery('#status').focus();
   return false;
  }
  if(username == ''){
   alert('Please enter your username.');
   jQuery('#username').focus();
   return false;
  }
  $.ajax({
   type : "POST",
   url : 'send_update.php',
   dataType : "json",
   data: { update : status, username : username },
   beforeSend: function(){
    jQuery('#update_btn').val('Updating...');
   },
   success : function(msg) {
    if( msg.success ) {
     //do nothing
    } else {
     //alert(msg.errormsg);
    }
    jQuery('#update_btn').val('Update');
   },
   error: function(msg) {
   }
  });
 });
});

Written by

Arvind is a web developer, programmer and blogger. He has expertise in PHP, Magento, WordPress, jQuery, JavaScript, HTML5 and CSS3. He loves to develop good looking websites with strong backend.

4 comments :

  1. Great tutorial!
    hi. this is not working in local host environment. any idea?

    ReplyDelete
  2. @xihad, It works ok in localhost environment. Please check you API settings. May be something is wrong there.

    ReplyDelete
  3. Hello there!

    Keep up the great piece of work, I read few posts on this web site and I think that your blog is really interesting and has got lots of superb information.


    Wall insulation

    ReplyDelete
  4. hey its not not working in google chrome browser..........

    ReplyDelete

We would love to hear from you...

 

© 2014 Web Speaks . All rights resevered. Designed by Templateism