European ASP.NET Hosting Tutorial :: Creating a Basic Chat System on a Website using AJAX

Chat application is very common in web today. In this post, we will explain you how to create a simple chat application using PHP, AJAX and MySql. The chat application that we are building is very simple. It include a start form where user enter his email address and also enter his friend email which he want to chat and same thing done by his friend we use these email as unique and send their message to each other.

Four blank white speech bubblesFollow these steps to create a basic chat system using AJAX:

Step 1: Create The Database Structure

Every chat room needs to keep the content of the chat lines stored somewhere. Some solutions use sessions, others use text files, but the most robust solutions use a database. So next time when you chat with some one, keep in mind it is saved somewhere there. 🙂

For a simple chat room system we will need just one table, it stores the nickname of the user, what he said and the time when he said it. It is also useful to have something to distinguish what each user said. My proposal is to have a color field so we can show each user chat lines in a different way.

I have named the table “chat” for obvious reasons. It contains an ID field which is the primary key and so it is auto-incremented, a nickname, color and chattext fields, strings with different lengths. The chattime field is a timestamp field for which MySQL will set as default value to the current time. This is how we know when the chat line have been submitted. The table uses the MyISAM engine and character set is UTF-8 as it supports most languages.

Step 2: Create The Frontend

Every good chat system has some kind of user management system. In our case we have just a user name. It is not complete solution but it is enough for the purposes of this tutorial.

When a user comes to the chat room page he needs to have a user name, so first we need to give him a way to choose one. Later we need to store this user name, so we do not need to ask him to enter his name every time he sends a message. That is why we will use sessions.

Here we create two sections in the frontend file: one for login and the other for chat. When the user comes for the first time, he will not have a user name in the session, and he will get a form to write down his user name and choose a color. When he submits the login form, the browser will be redirected to the chat screen. It is the same URL but the user sees one section a time.

Login section

Login section consists of two parts. The form on which the user provides his user name and color. Then he submits the form which will be handled by a script to set the session. After the browser returns to the first page again but now showing the chat interface instead of the login form. Let us create the first section with a script file named index.php:

 First thing we do in this script is to call start_session(). We need to start the session before we print anything on the screen. After that a simple test, if the user has not registered his user name in the session we will show the form. If he did go through the login form, we show what is after the “else” keyword. Now it is empty but later we will add code there.

So if $_SESSION[“usrname”] variable is empty, we show a form. Very simple, one table in a form with two fields: nickname and color. The user enters a user name and chooses a color from the dropdown select element. Then clicks on submit button that will submit the form to the login.php script.

Now let us create a simplified version of the login.php script. We are not fully validating the submitted values here for simplification reasons, but for security sake it is wise to assure the submitted values are valid.

 Again, the first thing we do is to start our session with session_start(). We will do that many times. Do some basic filtering of the user name and color provided via the form, and assign the values to session variables. Then we redirect the user back to index.php page using the header() function. This time we have a session set with the user name value, so the if statement will activate the second part of the script this time.

Chat Section

The second interface of this application is the chat window itself. We need to copy this code to the last part of the index.php for else section between the curly brackets.

The JavaScript Section

An important file for the chat system is main.js. This is where our AJAX requests are being processed. We have three functions and one event listener. Copy this code in main.js file:

This chat application will retrieve the chat status every two seconds, but we do not want to retrieve all the past chat lines every time. We already retrieved the newest ones, so we need a way to track which lines were retrieved for the last time. As you may remember when we created the database table we added a primary key field named ID that is auto-incremented. We use that field value to track which line we have seen last. That is why we us a variable name lastTimeID in our JavaScript.

Step 3: Create The Backend Section

The backend are the server side PHP helper scripts that call the class. The helper scripts handle the AJAX requests  and call the class. We have two helper scripts, as mentioned before. We have refresh.php to refresh our chat window, and submit.php to submit new chat lines.

The Helpers

The first helper script is refresh.php. It receives the last chat line ID from AJAX and pass it to a static class method that returns a JSON encoded response. Then the script outputs that as response to the AJAX requests. The code below is refresh.php code:

Another file we need to create is config.php. it is a simple configuration file we are including in these two files where we define the database access variables.

The Main Class

The last file left to explain is the class itself. Let us copy this code in chatClass.php file:

To connect to the database we need login information, so use constant values defined separately with MySQL connection values like the server name, database name, MySQL username and password.

As a final note, we just would like to remind that database access operations may fail eventually due to unexpected errors. The code shown above does not contain all the error checks that it should tp be robust. Error checking was omitted to avoid making the code look more complicated just for this tutorial. Keep that in mind when implementing any kind of database access applications, so your code can be as robust as code written by a good professional developer.

hostforlifeasp.net AJAX Chat 8.3 Hosting

Ajax Chat 8.3 is a light-weight customizable web chat software implemented in JavaScript and PHP. The script does not require Java, Flash, or any other plugins. Features:

  • Public and private chat.
  • Login as a registered user or as a guest.
  • Away status, custom colors, smileys, user gender/status icons.
  • Ajax Chat can be integrated with a third-party membership system by implementing user authentication routine. Advanced integration options: if user is logged in to the website, they can be logged in to the chat automatically.

hostforlifeasp.net is the best and reliable Ajax chat 8.3 hosting that does not require flash. Ajax chat is known for its robust user interface and customizability. However, like many HTTP/AJAX chat scripts, typical installations to be very server intensive, and as a result, many webhosts (especially free webhosts) don’t particularly appreciate their presense. Our goal is to provide hosting for ajax chats on our fine tuned servers, designed to make it easy to install a great chat room on your website without dealing with the costs involved. We also have added our own administration panel for all chat rooms, allowing you to perform basic configuration and setup without the technical details involved in setting up a normal installation of an Ajax Chat 8.3.

If you are looking for a powerful, non-IRC AJAX/PHP chat room script, Ajax Chat 8.3 may be worth considering. If you are unsure of what our AJAX Chat 8.3 hosting has to offer, just visit our official website . Whether you are running a small chat room for personal meetings, or a full chat room for your forum or website, we hope that you will consider hosting your chat with us!

hostforlifebanner