HOME  |  AJAX  |  SOLUTIONS  |  TECHNOLOGIES  |  E-COMMERCE  |  ABOUT US
The Backend

Now it's time to create the back-end to the chat application.  The way we have setup our client-side, all requests go to the same URL.  The backend decides how to handle this based on the parameters passed with the request.

The first thing that our back-end file does is create some HTTP headers to keep the clients brower from caching the respose.
//Send some headers to keep the user's browser from caching the response.
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-Type: text/xml; charset=utf-8");
You can see that we set the "Expires" header to a date that has already passed.  Without this line, IE tends to cache the response regardless of the other headers. 

The one other header we send is the Content-Type.  We set our content type to text/xml so the clients browser knows that we are sending an XML file rather then a text file.  This eases the creation of the XMLDoc object for the different browser types.

The next line includes a file that contains our database functions.  I like to abstract my database functions in a seperate file in case I need to change by database connection type (MSSQL, Oracle, etc.). 
require('database.php');
I'll explain this file in a little bit.

The first action that we perform is to check our POST variables to see if a new message was sent in the request.
//Check to see if a message was sent.
if(isset($_POST['message']) && $_POST['message'] != '') {
$sql = "INSERT INTO message(chat_id, user_id, user_name, message, post_time) VALUES (" .
db_input($_GET['chat']) . ", 1, '" . db_input($_POST['name']) .
"', '" . db_input($_POST['message']) . "', NOW())";
db_query($sql);
}
If a new message was sent, then we add the message to our database. $sql is a string containing the query text.  We use to the function db_input to escape any quote characters that the user may have entered.  We then execute the query text with our db_query function.

Next we'll check to see if a request to reset the chat was sent:
//Check to see if a reset request was sent.
if(isset($_POST['action']) && $_POST['action'] == 'reset') {
$sql = "DELETE FROM message WHERE chat_id = " . db_input($_GET['chat']);
db_query($sql);
}
Once again we create our query text and execute it with our db_query function.  This query simply deletes all messages from the database that are from the current chat session.

Now it's time to create the response that will get sent back to the use.  After we have finished updating the database with any new messages sent by the user, we will get the list of any new messages that the user hasn't recieved yet.

We start by creating our XML header and document element opening tag.
//Create the XML response.
$xml = '<?xml version="1.0" ?><root>';
It is important to note that there cannot be any whitespace or other characters before our XML declaration, otherwise we will run into processing errors when trying to parse the XMLDom on the client-side.

Next, we will check to see if the user is in a chat room.  If not we will send the user a message informing them that they need to enter a chat room before they can get any chat messages.
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$xml .='Your are not currently in a chat session. <a href="">Enter a chat session here</a>';
$xml .= '<message id="0">';
$xml .= '<user>Admin</user>';
$xml .= '<text>Your are not currently in a chat session. ';
$xml .= '&lt;a href=""&gt;Enter a chat session here&lt;/a&gt;</text>';
$xml .= '<time>' . date('h:i') . '</time>';
$xml .= '</message>';
We have an empty link in this message that we can later replace with a URL to our chat room selection page, but that is beyond the scope of this tutorial.

If the user is in a chat room, then we will get every message that the user hasn't received yet and add them to our XML response.
} else {
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
$sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') as post_time" .
" FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
$message_query = db_query($sql);
while($message_array = db_fetch_array($message_query)) {
$xml .= '<message id="' . $message_array['message_id'] . '">';
$xml .= '<user>' . htmlspecialchars($message_array['user_name']) . '</user>';
$xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
$xml .= '<time>' . $message_array['post_time'] . '</time>';
$xml .= '</message>';
}
}
The first step here is to check and see if the user has recieved any messages yet.  If the request didn't specify the last request recieved, then we set the $last variable to zero in order to get every previous message for this chat session

Next, we create our SQL statement to get all the message for the current chat session that were posted since our last update.  By limiting our request to just the messages that we haven't recieved yet, we reduce the amount of network traffic we need to send as well as limit the client site work involved.

After we have performed our query, we loop through each message row and add a message node to our XML.  Each message node contains the message id, the user who posted the message, the text of the message, and the time the message was posted.

Finally, we close out our XML document element and add our XML to the response.
$xml .= '</root>';
echo $xml;
We are now ready to test out our Chat Function. 
Be sure that you have created the database tables and set the correct database connection value in database.php.