Creating a jQuery-based Chatbox

Creating a jQuery-based Chatbox
Difficulty: Easy
Description: Create a live chatbox that automatically updates itself.
Author: M@ster; Date Added: 2009-09-06; Views: 23688
I spent a long time searching the internet on how to create an jquery chatbox that would automatically update itself everytime someone would post. Not having any luck I was forced to create it myself.

Here's what it will basically look like, without any additional styling or CSS:

Some things you will need to know:

Most hosts will provide these except Jquery which you will have to download from their site.

The beginning
First of all we need to start out with our mysql table otherwise none of this will work. You will also have to create a mysql database if you do not already have one.
CREATE TABLE `chatbox` (
  `name` VARCHAR( 255 ) NOT NULL ,
  `timestamp` INT( 255 ) NOT NULL ,
  `message` TEXT NOT NULL

Now that we have set up our table we now have to connect to it. This will be done in our config.php file.

// Connect to database
 $dbhost = 'localhost'; // Where your mysql host is located. You most likely won't have to change this.
 $dbuser = ''; // Database user
 $dbpass = ''; // User password
  $dbh = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
 $dbname = ''; // Name

// date stuff
 $date_format = 'd/M/Y H:i:s'; // This is how the date will be displayed to other people.

// The parsing function. You can allow it to parse BBCODE if you wish.
 function Parser($text) {
   $text = str_replace("
", "", $text);
  return $text;

<style type="text/css">
.error {
 background-color: #ff8989;
 padding: 5px;
 width: 380px;
.good {
 background-color: #89ff91;
 padding: 5px;
 width: 380px;

In the code it explains how to set it up. Just change the variables. As for the CSS that can be changed to display whatever error style message you want. The config.php file allows your chatbox to connect to the mysql database which will let you add new messages and retrieve new ones.

Ok now that we have all that taken care of we can get to the real fun part! Lets first figure out our javascript:

Index.php file
<script src=""></script>

This grabs the javascript file from This is how most of the magic happens or at least the part where it retrieves the new messages and then displays them.
<script type="text/javascript">
// This is used to submit your message into the database.
function SubmitMessage() {
  var name = document.getElementById('name').value;
  var message = document.getElementById('message').value;
    $("#load").load("new_message.php", { 'chat[]': [name,message] }).fadeIn(1000);
      setInterval("FadeOutLoad();", 5000);
// Just fades out the above ^
function FadeOutLoad() {
function LoadNewMessages() {
  // Loads new messages from retrieve_new.php file into new_posts div

   // Determines whether or not there is a new message by searching new_posts div
    if (document.getElementById('new_posts').innerHTML != '') {

    // If nothing exists it won't do anything but if there is it will post this:
"); // This makes it fade in. Not necessary but cool. $('#new_message').fadeIn(1000); // Empties the div for future posts. $('#actions').html(""); } } // Refreshes and checks for new messages. setInterval("LoadNewMessages();", 1000); </script>

Most of it is explained above, but without this your neat little chatbox you want would not work at all. This passes the information back and forth from the server to your browser.

This next part includes a little PHP. This is the start of your div/box that will display the messages in. When a user loads the page the older messages will already be displayed in the box which can be adjusted to whatever size you want. It only loads in 50 but you can change the limit in the query.
// Require Config.php file
 require_once 'config.php';

 // Retrieve messages from database
  $query = mysql_query("SELECT message, name, timestamp FROM chatbox ORDER BY id DESC LIMIT 50");
  while ($row = mysql_fetch_assoc($query)) {

   echo "".$row['name']." - ".date($date_format, $row['timestamp'])."".Parser($row['message'])."";


End of display messages box.

This next part is where your input gets feed from the textarea to the database. The new_posts is also where new messages are temporarily stored.
<div id="new_posts" style="display: none"></div>
<div id="load" style="display: none"></div>
Name: <input type="text" id="name"><br>Message:<br>
<textarea rows="4" id="message" cols="39"></textarea><br>
<input type="submit" value="Submit" onclick="SubmitMessage();">

This is now the end of Index.php file.

This new_message.php file takes your text you typed and inserts it into the mysql database.
// Get config.php
 require_once 'config.php';

 // Variables
  $name = strip_tags($_POST['chat']['0']);
  $message = strip_tags($_POST['chat']['1']);

  if (empty($name) || empty($message)) {
   echo "Please fill in all fields!";
  } else {

    // Inserts into mysql
     mysql_query("INSERT INTO `chatbox` ( `id` , `name` , `timestamp` , `message` ) VALUES (NULL , '$name', '".time()."', '$message')");

      echo "Message added!";

Once again pretty easy to understand you can change the error and good around to display whatever kind of message you want your user to see. The strip_tags() just takes all the html out so people can't post images or links... you can change that if you want. Otherwise this just inserts it into the database, nothing else special about it.

Last but not least we have the retrieve_new.php file which retrieves the new messages and then places them within a div which can be changed around however you want.
// Fetches the config.php and connects to database.
 require_once 'config.php';

 // Gets the new messages
  $query = mysql_query("SELECT * FROM chatbox WHERE timestamp='".(time() - 1)."'");
  $num = mysql_num_rows($query);

   while($row = mysql_fetch_assoc($query)) {

    echo "".$row['name']." - ".date($date_format, $row['timestamp'])."".Parser($row['message'])."";


Other than the echo part nothing else should really be changed otherwise it won't work right (possibly).

That's it for the tutorial, and I hope it helped someone.

Enjoy, M@ster.