PHP Ajax Shoutbox Tutorial

In this tutorial we will create a simple PHP shoutbox with Ajax based messaging. It will ask the user to choose a nickname and then allow him/her to use it (no registration and password will be required).

The Database

Given these requirements, we will only need 2 tables. I am giving them in pseudo-SQL code:

Table users:
id INT PRIMARY KEY
username VARCHAR(30)
last_action DATETIME

Table messages:
id INT PRIMARY KEY
user_id INT FOREIGN KEY to users.id
message TEXT

We will not require user registration but will still need to ask them to choose username. At the time of selecting it we will insert it into users table and will store it in session.

The Chat Box

The chat box contains two main parts – the text box where you enter messages and the area which shows the messages posted.

Here is the input code:

<p><textarea id=”myMessage”></textarea>

<input type=”button” value=”Send” onclick=”sendMessage();”></p>

I’m leaving the formatting to you. Then there will be also a div where the latest 10 messages will be displayed:

<div id=”chatArea”></div>

The Javascript Functions

There are 2 javascript functions needed: one will send messages, the other will retrieve them from the DB. The second function will be called when the document is loaded and refreshed in 10 seconds interval. It will also be called immediately when you post a message so you can see your own message without any delay.

For easy work with Ajax and DOM, download and install JQuery. We will use the library in this tutorial.

function sendMessage()
{
     $.ajax({
          type: "POST",
          url: "post.php",
          async: false,
          data: "message="+$("#myMessage").val(),
           success: function(msg){
                refreshChat();
           }
      });
}

This simple function just sends your message. Note that the function has async:false. This is because we clearly want posting to happen prior to refreshing the chat.

And this one is loading the chats:

function refreshChat()
{
      $.ajax({
          type: "POST",
          url: "chat.php",
           success: function(msg){
                $("#chatArea").html(msg);
           }
      });
}

This function is pretty simple too: it gets the chats from chat.php and displays the returned HTML in chatArea.

You need also to ensure this function runs all the time even if the user performs no action. To do this add the following javascript somewhere at the bottom of the HTML page with the chat:

window.setInterval(“refreshChat()”,10000);

The PHP Code

The script for posting chat message should be something like this:

<?php
session_start();

$q=”INSERT INTO messages (user_id,message) VALUES (‘$_SESSION[user_id]‘,
\””.addslashes($_POST['message']).”\”)”;

mysql_query($q);
?>

And the script which retrieves the last 10 chat messages:

<?php

$q=”SELECT tM.*, tU.username as username
FROM messages tM JOIN users tU
ON tU.id=tM.user_id
ORDER BY id DESC LIMIT 10″;
$result=mysql_query($q);

while($row=mysql_fetch_array($result))
{
echo “<p>”.$row['username'].” says: “,nl2br($row['message']).”</p>”;
}
?>

Here in the query we join the two tables to get the username along with the message. The output of the script is sent directly to the javascript function.

What To Do Further

This is a very simple php ajax chat. The code is missing few things which you can add once you understand it and make it working:

  • Add date/time to messages
  • Add error checking in case some query fails
  • Make sure the user does not post empty message (you can add validation code to the javascript functions.
  • Make sure the user does not enter malicious code in the chats
  • The tutorial does not include the user registration part. You will need to do it yourself.

If you want to see similar script in action, check my free php chat software.


4 thoughts on “PHP Ajax Shoutbox Tutorial

  1. Michael

    I actually go several steps further going into a full Ajax Comment system. I go about it including Modification functions, BBCode, in addition.

    For the basics this is a fantastic tutorial.

Leave a Reply