Facebook’s Chat application is more social and it has a good user base. Making a simple chat application like Facebook is pretty much simple. In this post i will show you how make a simple chat application just like facebook.

chat application like facebook

Database Design

There are two tables in this design, users and chat. This schema design does not implement real authentication system. It just simulates a situation where both the users are logged in by passing the user id through the browser address bar i.e as a parameter.

The chat table has a foreign key reference to the users table id field.

facebook_like_chat_app

Chat Application Like Facebook

The Chat Class (FbChatMock) contains the core methods for adding and retrieving the chat messages from the database. This class also connects to the database when the object is first created.

The methods in this class is easy to understand. The addMessage() method adds the user provided message by escaping it through real_escape_string and adds the message into the database. The user id is casted into an integer so that nothing gets inserted other than integer value.

The getMessages method makes a JOIN statement with both the users and chat table on the user_id field.

FbChatMock.php

Just add the database configuration.

Chat page

The chat.php page initially fetches the previous chat messages if there is one and displays it. This page is the main chat page. Here is where the user is stored in the session which is got from the query parameter
chat.php

Ajax Components

There are two main ajax pages,
1. add_msg.php – Adds the messages entered by the user to the database.
2. get_messages.php – Retrieves the messages from the database.

add_msg.php

get_message.php

JavaScript

This scripts helps in getting the messages with an interval of 20 seconds for each messages fetching. The binding of users keyboard event is also done in this script. jQuery is needed for this scripts to work properly.
chat.js

Click to download
Click to download