• Translate

8/31/2017

Tutorial Creating Shoutbox With PHP MySQL And JQuery

Tutorial PHP |

Advertisement

Shoutbox is a chat-like feature of multiple websites that allows people to leave messages immediately on the website, generally without a user registration form.

In its simplest form, shoutbox is just a short message, probably with information about the author. Pages can be refreshed automatically after a certain interval, or dynamically surveyed to keep new messages visible. Older posts are often deleted after a number of messages have been written to save space on the server.

We will create a shoutbox with facebook look like in the picture below

Shout Box

Steps to Create a Shoutbox

1. 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.
.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;
}

2. 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. 
<!-- shoutbox -->
<div class="shout_box">
<div class="header">Shout Box <div class="close_btn">&nbsp;</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 -->

3. 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. 
//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. 
//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. 
//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');
    }
});

4. 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
####### db config ##########
$db_username = 'root';
$db_password = '';
$db_name = 'table';
$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 kidding me?');
        exit();
    }
}

5. Create a Database table.sql

CREATE TABLE IF NOT EXISTS `shout_box` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(60) NOT NULL,
  `message` varchar(100) NOT NULL,
  `date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip_address` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
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!



Disclaimer: Images, Content of articles or videos that exist on the web sometimes come from various sources of other media. Copyright is fully owned by the source. If there is a problem with this matter, you can contact us here.
How to style text in Disqus comments:
  • To write a bold letter please use <strong></strong> or <b></b>.
  • To write a italic letter please use <em></em> or <i></i>.
  • To write a underline letter please use <u></u>.
  • To write a strikethrought letter please use <strike></strike>.
  • To write HTML code, please use <code></code> or <pre></pre> or <pre><code></code></pre>, and please parse the code in the parser box below.
Show Parser Box