In this tutorial I will teach you how to make an Shout-Box like the one on Facebook using PHP and jQuery .The little chat box from Facebook doesn’t take up much space and people cand instantly interact with their friends. Let’s create an Shout Box similar to Facebook chat box .
CSS Code for Facebook chat style
Should work in Chrome, Firefox and ie8+.
| .shout_box_fb { 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; } .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; } time{ font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif; font-weight: normal; float:right; color: #D5D5D5; } |
Shout Box HTML
Look at Shout Box markup, you can see username , mesagge fields and the div with “message_box” class, wehere user messages are loaded from the database .
| <!-- shoutbox --> <div class="shout_box_fb"> <div class="header">RollCode Shout Box <div class="close_btn"> </div></div> <!--Change the name in what you want--> <div class="toggle_chat"> <!--toggle_chat Class from css file--> <div class="message_box"> <!--message_box Class from css file--> </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 and Hit Enter" maxlength="100" /> </div> </div> </div> <!-- shoutbox end --> |
jQuery
We will refresh chat every second using setInterval() – it sends ajax call to shot.php and loads returned data into the element . So the Shout Box get updated with any newly added message .
| //automatically refresh after every 1 second. 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 one thing and hit enter key, we want to send entered information to shout.php. The keypress() technique triggers once a button is pressed down, and (evt.which == 13) condition makes positive key pressed is Enter key, then we are able to proceed with Ajax $.post() method, as shown in example below. you’ll replace keypress() with .click() method, however you wish to feature button in your HTML.
| //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); }); } }); |
And the example below slides up or down Shout Box when a user clicks close or open icon .
| //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 for changing close/open icon image if(toggleState == 'block') { $(".header div").attr('class', 'open_btn'); }else{ $(".header div").attr('class', 'close_btn'); } }); |
And finally, PHP
Content of PHP file
shout.php with some MySQL query:
| <?php ####### DataBase config ########## $db_username = 'Your db user'; $db_password = 'Your db password'; $db_name = 'Name of database'; $db_host = 'localhost'; ####### End of DataBase config ########## ####### Queryes in db ########## 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(); } } |
So, that’s all folks ! I hope you enjoy it !
No comments:
Post a Comment