Creating Shoutbox with jQuery & PHP Facebook Style

Facebook has this nice little chat box that doesn't take up much space, and people can instantly interact with their friends, it is a cool feature to have in any website. Let's get inspired and create an similar shoutbox which will look similar to Facebook chat box. Shout Box Facebook Style

Style

Here's the CSS, I've tried to make it look close as possible to Facebook chat box. Should work in Chrome, Firefox and ie8+. Let me know if it requires some tweaking in other browsers.
CSS
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
.shout_box { background:#627BAE; width:260px; overflow:hidden; position:fixed; bottom:0; right:20%; z-index:9; } .shout_box .header .close_btn { background: url(images/close_btn.png) no-repeat 0px 0px; float:right; width:15px; height: 15px; } .shout_box .header .close_btn:hover { background: url(images/close_btn.png) no-repeat 0px -16px; } .shout_box .header .open_btn { background: url(images/close_btn.png) no-repeat 0px -32px; float:right; width:15px; height:15px; } .shout_box .header .open_btn:hover { background: url(images/close_btn.png) no-repeat 0px -48px; } .shout_box .header{ padding: 5px 3px 5px 5px; font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif; font-weight: bold; color:#fff; border: 1px solid rgba(0, 39, 121, .76); border-bottom:none; cursor:pointer; } .shout_box .header:hover{ background-color: #627BAE; } .shout_box .message_box { background: #FFFFFF; height: 200px; overflow:auto; border: 1px solid #CCC; } .shout_msg{ margin-bottom: 10px; display: block; border-bottom: 1px solid #F3F3F3; padding: 0px 5px 5px 5px; font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif; color:#7C7C7C; } .message_box:last-child { border-bottom:none; } time{ font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif; font-weight: normal; float:right; color: #D5D5D5; } .shout_msg .username{ margin-bottom: 10px;margin-top: 10px; } .user_info input { width: 98%; height: 25px; border: 1px solid #CCC; border-top: none; padding: 3px 0px 0px 3px; font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif; } .shout_msg .username{ font-weight: bold; display: block; }

Shout Box HTML

Have a look at Shout box markup, you can see username and message fields, also the div with "message_box" class attribute, where user messages are loaded from the database.
HTML
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
<!-- shoutbox --> <div class="shout_box"> <div class="header">Saaraan Shout Box <div class="close_btn"> </div></div> <div class="toggle_chat"> <div class="message_box"> </div> <div class="user_info"> <input name="shout_username" id="shout_username" type="text" placeholder="Your Name" maxlength="15" /> <input name="shout_message" id="shout_message" type="text" placeholder="Type Message Hit Enter" maxlength="100" /> </div> </div> </div> <!-- shoutbox end -->

jQuery

Using setInterval(), we will refresh chat every 1000 milliseconds, it sends ajax call to shout.php and loads returned data into the element, updating shout-box with any newly added message.
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
//automatically refresh after every 1000 milliseconds. load_data = {'fetch':1}; window.setInterval(function(){ $.post('shout.php', load_data, function(data) { $('.message_box').html(data); var scrolltoh = $('.message_box')[0].scrollHeight; $('.message_box').scrollTop(scrolltoh); }); }, 1000);
When user writes something and hit enter key, we need to send entered data to shout.php. The keypress() method triggers when a button is pressed down, and (evt.which == 13) condition makes sure key pressed is Enter key, then we can proceed with ajax $.post() method, as shown in example below. You can replace keypress() with .click() method, but you need to add button in your HTML.
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
//method to trigger when user hits enter key $("#shout_message").keypress(function(evt) { if(evt.which == 13) { var iusername = $('#shout_username').val(); var imessage = $('#shout_message').val(); post_data = {'username':iusername, 'message':imessage}; //send data to "shout.php" using jQuery $.post() $.post('shout.php', post_data, function(data) { //append data into messagebox with jQuery fade effect! $(data).hide().appendTo('.message_box').fadeIn(); //keep scrolled to bottom of chat! var scrolltoh = $('.message_box')[0].scrollHeight; $('.message_box').scrollTop(scrolltoh); //reset value of message box $('#shout_message').val(''); }).fail(function(err) { //alert HTTP server error alert(err.statusText); }); } });
Example below slides up or down shout box, when user clicks close or open icon.
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
//toggle hide/show shout box $(".close_btn").click(function (e) { //get CSS display state of .toggle_chat element var toggleState = $('.toggle_chat').css('display'); //toggle show/hide chat box $('.toggle_chat').slideToggle(); //use toggleState var to change close/open icon image if(toggleState == 'block') { $(".header div").attr('class', 'open_btn'); }else{ $(".header div").attr('class', 'close_btn'); } });

PHP

Here's PHP file shout.php, as you can see I have sanitized post variables using PHP filter_var(), and performed some MySQL query. Since I don't want to grow this database table large, I am keeping only 10 recent rows in the database, everything else will be deleted. It is up to you to decide how many rows you want to keep.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
<?php ####### db config ########## $db_username = 'xxxx'; $db_password = 'xxxx'; $db_name = 'xxxx'; $db_host = 'localhost'; ####### db config end ########## if($_POST) { //connect to mysql db $sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database'); //check if its an ajax request, exit if not if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { die(); } if(isset($_POST["message"]) && strlen($_POST["message"])>0) { //sanitize user name and message received from chat box $username = filter_var(trim($_POST["username"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH); $message = filter_var(trim($_POST["message"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH); $user_ip = $_SERVER['REMOTE_ADDR']; //insert new message in db if(mysqli_query($sql_con,"INSERT INTO shout_box(user, message, ip_address) value('$username','$message','$user_ip')")) { $msg_time = date('h:i A M d',time()); // current time //output message echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$username.'</span><span class="message">'.$message.'</span></div>'; } // delete all records except last 10, if you don't want to grow your db size! mysqli_query($sql_con,"DELETE FROM shout_box WHERE id NOT IN (SELECT * FROM (SELECT id FROM shout_box ORDER BY id DESC LIMIT 0, 10) as sb)"); } elseif($_POST["fetch"]==1) { //Retrive last 10 messages from Database $results = mysqli_query($sql_con,"SELECT user, message, date_time FROM (select * from shout_box ORDER BY id DESC LIMIT 10) shout_box ORDER BY shout_box.id ASC"); while($row = mysqli_fetch_array($results)) { $msg_time = date('h:i A M d',strtotime($row["date_time"])); //message posted time //output messages echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$row["user"].'</span> <span class="message">'.$row["message"].'</span></div>'; } } else { //output error header('HTTP/1.1 500 Are you kiddin me?'); exit(); } }
That's it! I hope this tutorial has helped you understand how shoutbox works and how we can make it look like Facebook chat box. By the way, I do want to see it working live in your website, so if you are using this example, please do share your links here and good luck!

Download Demo

  • Hi, I have installed the shout box, but after I press enter with a message, it came back with an pop-up error"Internal Server Error". Strange also is this: in error_log file I have: "PHP Parse error: syntax error, unexpected 'table' (T_STRING) in /home/blabla/public_html/ciatbox/shout.php on line 6" and my line 6 looks like this "$db_name = 'table';" Any help will be appreciated, thanks
  • Well I just found this and its perfect for what I want to do. So going to start shedding this code to fit my needs. Thanks.
    • JUST GO TO SHOUT.PHP EDIT YOUR LOCALHOSTNAME AND DB.. AND IMPORT YOUR DATABASE.
New question is currently disabled!