How to create a chat box using jquery and php

Yo! what’s up? It’s been 2  weeks since my last post so I ‘m going to try to make up for those 2 weeks that I haven’t posted anything on my blog.

In this tutorial I’m going to show you how to build a simple chat box using jQuery and php.

 

Requirements

 

Resources

I guess this is a new portion so let me introduce to you what resources is. Resources is where you can find the links to some of the sites that in one way or another has given me an idea on how to build something. In this case a chat box.

 

Procedure

First thing that you have to do is to create your working folder where you will put all the files for this mini-project.

Next, create the database where we are going to store the user information and messages.

Here’s the table structure for users:

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

And the table structure for the chat box:

CREATE TABLE IF NOT EXISTS `chat_box` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sender` varchar(30) NOT NULL,
  `sendto` varchar(30) NOT NULL,
  `message` varchar(140) NOT NULL,
  `date_sent` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=33 ;

You can use the table structures above. But you can also build your own if you want. Since what I’m showing you is very minimal. You might want to add up some fields and other tables as well.
You might also want to insert some data on the table for users using phpmyadmin or any database manager that you know. Since were not going to create a page where the users can register.

 

Next, create a page where the users can login.

<?php require_once('tutorials_config.php'); //database configuration file ?>

<!-—form—-> <form action="login.php" method="post"> <p> <label for="username">Username:</label> <input type="text" name="username" id="username"> <input type="submit" value="login"> </p> </form> <?php

//form processing if(!empty($_POST)){ $username = clean($_POST['username']); $exist = $db->query("SELECT username FROM users WHERE username='$username'"); if($exist == 1){ header('Location:test.php'); //redirect to chatbox page $_SESSION['user_logs'] = $username; //create a session for user }else{ header('Location:login.php'); //redirect to login page } } ?> <?php

//sanitize user input function clean($str){ return trim(mysql_real_escape_string($str)); } ?>

First, you have to include your database configuration file at the uppermost portion of your php file. Then create an html form. You might have notice that I only have a text field for the user id. You can also modify the code and add a password if you want. But as I have said earlier, I want to keep things as minimal and simple as possible. Please read the comments in the code to help you understand what it does.

If we have a login, we also need to have a logout.

<?php
session_destroy(); //destroy the session created from login page
header('Location:login.php'); //redirect to login page
?>

Again, this code is very minimal. It actually destroys the whole session. So if one person logs out, all the other people who is currently logged in will also be logged out. You can always improve this one if you like. That is by looping through all the users in the session and unsetting only the session for the user who wants to logout.

 

We’ve arrived at the point of interest. The chat box itself.
First, include the database configuration file. And check if a user session is already set:

<?php

require_once('tutorials_config.php');


if(empty($_SESSION['user_logs'])){ //check if user session is set
    header('Location:login.php'); //redirect to login page if user session is not set
}

?>

Next, include the files that you have downloaded earlier from the links in the requirements portion. The jquery file, jquery ui files, and the jquery chat box plugin files.

<link rel="stylesheet" href="ui-lightness.css" type="text/css" media="screen" />
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript" src="jq_ui.js"></script>    
<link type="text/css" href="jquery.ui.chatbox.css" rel="stylesheet" />
<script type="text/javascript" src="jquery.ui.chatbox.js"></script>

After that, create the html form for the chat box.

First, the link to the logout page. And the hidden field where we are going to store the username. I always use hidden fields when I want to store php generated values which I want to access through javascript later on. I don’t know what tricks you are using to achieve the same thing. But that’s the one that I’m using.

<p>
<a href="logout.php">Logout <?php echo $_SESSION['user_logs']; ?></a>
</p>
<input type="hidden" id="username" value="<?php echo $_SESSION['user_logs']; ?>">

Next, also create a text field where the user can choose whom to send the message. I used an auto-suggest field to fetch the usernames from the database except the username of the user who is currently logged in. I have previously written an article discussing about datalist you can check it out if you don’t know how to use datalist yet. I also mentioned there that datalist doesn’t work for Chrome yet, and I have no idea when will they have it on Chrome. So use Firefox 5 or higher if you want to make this work. On the other hand, you can use jquery ui auto-suggest so that you can make it work on all browsers.

Also create a button which will call up the chat box.

<p>
	<label for="chatwith">Chat with:</label>
	<input type="text" name="chatwith" id="chatwith" list="otherusers">
	<datalist id="otherusers">
	<?php 
	$current_user = $_SESSION['user_logs'];
	$users = $db->get_results("SELECT username FROM users WHERE username != '$current_user'");	
	if(!empty($users)){
	?>
		<?php foreach($users as $v){ ?>
			<option value="<?php echo $v->username; ?>"><?php echo $v->username; ?></option>
		<?php } ?>
	<?php } ?>
	</datalist>
	</p>
	<input type="button" id="btn_chat" name="toggle" value="chat" />

Next create a div for the chat box. This is where all the conversations will show up.

<div id="chat_div">
</div>

Next, write the jquery code that will serve as the processor for all the stuff which we are going to do in the chat box. And that includes: selecting the receiver of the message, saving the message into the database, updating the contents of the chatbox so that the most recent messages will be previewed without refreshing the whole page.

First, let’s set what we want to do once the page loads.

$(function(){

$('#chat_div').hide();  setInterval(load_messages, 2500); var username = $.trim($('#username').val()); var box = null;

});

Here’s what the code above does:

  • $(function(){ .. });  – the built in jquery function which serves as an initializer. Its equivalent to the document.ready() function in javascript. Anything which goes inside it will get executed once the page loads
  • $(‘#chat_div’).hide(); – we hide the chat box div since the recent chat messages from the database will get loaded into the div which is not enclosed in the chat box
  • setInterval(load_messages, 2500); – we call the load_messages() function every 2500 milliseconds
  • var username = $.trim($(‘#username’).val()); – we store the username of the user
  • var box = null; – we set the value of the chat box to null ensure that it doesn’t store anything on page load

 

Next, we set what happens when the user clicks on the chat button. Remember that the user must first select another user to chat with before clicking on the chat button. But I guess I didn’t include the code that checks if the text field indeed contains a username which is stored in the database. So you might as well include that while you’re following this tutorial.

$("#btn_chat").click(function(event, ui) {
		  
      if(box){
         box.chatbox("option", "boxManager").toggleBox();
       }else{
       
          box = $("#chat_div").chatbox({id: username, user:{key : username}, title : "chat", 
                                                messageSent : function(id, user, msg){
													
	 $.post('send_message.php', {'username': username, 'sendto' : $.trim($('#chatwith').val()), 'message' : msg});
													
          $("#chat_div").chatbox("option", "boxManager").addMsg(id, msg);
                                                }});
              }
          });

Here’s what the code above does:

  • box.chatbox(“option”, “boxManager”).toggleBox(); – toggles the chat box. When the user clicks on the chat button for the first time the chat box shows up. And when the user clicks on it again, it hides.
  • box = $(“#chat_div”).chatbox(); – setting the options for the chat box.
      • id – the id of the user who currently uses the chat box
      • user – json string which stores the name of the current user
      • title – title of the chat box. In facebook the title is the name of the user you are chatting with
      • messageSent – what you want to do once the user sends the message(pressing enter). The function assigned to this variable has 3 return values. The id, user, and msg 
  • $.post(); – we call up a php script which inserts the message into the database. In the code above, we passed in 3 arguments: the sender, receiver, and message. Scroll down to the latter part of this tutorial to view the code for inserting the message into the database
  • $(“#chat_div”).chatbox(“option”, “boxManager”).addMsg(id, msg); – lastly we call up the addMsg() function which appends the name of the user and the message into the chat box

 

Next, write the function which calls up the php script which loads up the recent messages from the database. Scroll down to the latter part of this tutorial to view the code of the load_messages.php script. Remember that this is the function that we call from the setInterval() function so that it will be called up every 2500 milliseconds.

 function load_messages(){
	$('#chat_div').load('load_messages.php');
 }

Next, create a new php file and name it send_message.php. The code is pretty self-explanatory, it’s the one that we use to save the user information, message and current date into the database.

<?php
require_once('tutorials_config.php');

$username = clean($_POST['username']);
$sendto = clean($_POST['sendto']);
$message = clean($_POST['message']);
$date = date('Y-m-d');

$send_message = $db->query("INSERT INTO chat_box SET sender='$username', sendto='$sendto', message='$message', date_sent='$date'");
?>


<?php
function clean($str){
	return trim(mysql_real_escape_string($str));
}
?>

Next, create a new php file again and name it load_messages.php. This one is also self-explanatory, we just fetch the recent messages, and sender from the database. We only fetch the messages which has the same date as the current date.

<?php
require_once('tutorials_config.php');

$user = $_SESSION['user_logs'];
$date = date('Y-m-d');
$messages = $db->get_results("SELECT * FROM chat_box WHERE date_sent='$date' AND sendto='$user' OR sender='$user'");

if(!empty($messages)){
foreach($messages as $v){
?>


<b><?php echo $v->sender; ?> :</b> <?php echo $v->message; ?><br/>
	

<?php } ?>
<?php } ?>

 

Output
Here’s a sample output. Yep! that’s me talking to myself just to test if its really working. Of course, the auto-suggest didn’t work in Chrome, so I had to type the name manually.

image

 

Conclusion
I guess that’s it for this tutorial. You’ve learned how to create a very simple chat box using jquery and php. If you like this tutorial, please don’t forget to share it. Thanks for reading!

19 thoughts on “How to create a chat box using jquery and php

    • seems like there’s a lot asking for the files. Just wait guys I’ve created this from over a year ago so I’m still going to look for the file in my old computer. I’ll post the link here as soon as I find it.

  1. my dear wern i downloaded your given zip file but its not working fine in login.php its accepting username but not going to test.php the page is staying in login.php after giving username its not redirecting from login.php to test.php please rechek your file and give me new zip file with .sql to eannikalyankumar@gmail.com and also give me online demo link so that you and me will get better understanding how the problem is occuring.

    • like I said it won’t work out of the box. You have to properly configure tutorials_config.php which is one of the files that was required from test.php and login.php. The tutorials_config.php file should be in the same directory as those 2 files along with the ezsql library which can be found here: http://justinvincent.com/ezsql

      Don’t just say it doesn’t work and ask for the files because you’ll never learn anything by doing that.

  2. HI, I can send me a tutorials_config.php , because this missing in the file, or send me the full demo link , please thanks

  3. Great article, but there is a little bug on it.

    After post messages, chatbox is always hidden, and the content inside chat_div cannot appear.

    You just need to show the chat_div again, add the 3rd line below to your code:

    var box = null;
    $(“#btn_chat”).click(function(event, ui) {
    $(‘#chat_div’).show(); //Add this line to show posts inside chat_div

  4. saying the db variable is undefined
    ( ! ) Notice: Undefined variable: db in C:\wamp\www\login.php on line 16
    Call Stack
    # Time Memory Function Location
    1 0.0011 253352 {main}( ) ..\login.php:0

    ( ! ) Fatal error: Call to a member function query() on a non-object in C:\wamp\www\login.php on line 16
    Call Stack
    # Time Memory Function Location
    1 0.0011 253352 {main}( ) ..\login.php:0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s