Make Real-Time Live Chat System with PHP, MySQL, and AJAX
Creating a real-time chat application is one of the most interesting and popular web development tasks. This blog post will guide you through building a basic real-time chat system using PHP, MySQL, and AJAX. We will not go deep into the coding aspects but focus on how this system works and what each part does to bring everything together. Let's explore the architecture and processes that make this chat app functional and dynamic.
How to integrate live chat system on a website
Project Requirement file
For User side
- user_chat.php
- fetch_user_sms.php
- send_message.php
- admin_chat.php
- fetch_admin_sms.php
- send_message.php
1. Understanding the Architecture of the Chat System
A chat application involves multiple parts working together to ensure real-time communication between the user and admin (or other users). These parts include:
- Frontend: This is the user interface where users interact with the chat system. It consists of HTML, CSS, and JavaScript (with AJAX to send and receive messages without reloading the page).
- Backend: This is the server-side logic handled by PHP, which connects to the database and processes the requests.
- Database: MySQL is used to store the messages exchanged between the users and admin, ensuring persistent data that can be fetched and displayed at any time.
Each of these components plays a crucial role in enabling real-time chat functionality.
2. Setting Up the Database
The database is the backbone of this system. In this chat application, the database named live_chat
holds a messages
table where each message exchanged between users is stored. The table typically has columns for:
id
: A unique identifier for each message.message
: The content of the message.sender
: This indicates who sent the message (either the user or the admin).created_at
: The timestamp when the message was sent.
This structure allows the system to track and display conversations in the correct order, offering a seamless experience for users.
3. Handling Chat Functionality on the Frontend
The frontend is where users interact with the chat system. It consists of a simple chat interface with the following components:
- Chat Box: The central area where users can see their messages and send new ones.
- Messages Section: The part that displays the chat history. It automatically updates by fetching messages from the database without reloading the page. Messages are dynamically styled based on whether they come from the user or the admin.
- Message Input: This is the text box where users type their messages. Once the message is submitted (by pressing a button or hitting 'Enter'), it is sent to the server via AJAX.
4. Using AJAX for Real-Time Communication
AJAX (Asynchronous JavaScript and XML) plays a key role in making the chat system real-time. It allows the frontend to communicate with the server without refreshing the entire page. The chat system uses AJAX in two ways:
- Fetching Messages: Every few seconds, the frontend sends an AJAX request to the server to fetch new messages from the database. Once the server responds with the messages, they are dynamically displayed in the chat window.
- Sending Messages: When a user sends a message, an AJAX request is sent to the server, passing the message content and the sender's information. The server then stores this data in the database and responds to the frontend.
This asynchronous communication ensures that users see new messages in real-time without experiencing any delays or interruptions.
5. Backend: Storing and Fetching Messages
The backend is powered by PHP, which connects to the MySQL database to store and retrieve messages. Here's how it works:
- Sending Messages: When a user sends a message, PHP handles the incoming request and stores the message and sender information in the
messages
table. This operation is simple, using anINSERT
query to save the data. - Fetching Messages: Periodically, the frontend requests new messages from the server. PHP fetches all the messages from the database (or only the new ones, depending on how it's configured) and returns them as HTML elements that are injected into the chat window.
6. Auto-Scrolling and Message Formatting
To improve the user experience, the chat system automatically scrolls to the latest message when new messages arrive. This is achieved by manipulating the DOM using JavaScript, ensuring that the chat window always stays at the bottom, where the most recent messages are located.
Additionally, messages from the admin and users are styled differently. For example:
- Admin messages might have a blue background, white text, and be aligned to the right.
- User messages could have a gray background, black text, and be aligned to the left. This visual distinction makes it easy for users to follow the conversation.
7. Clearing the Chat History
The chat system also includes a feature to clear the chat history. When the user or admin clicks the "delete" button, an AJAX request is sent to the server to delete all messages from the database. Once the messages are deleted, the frontend is updated to reflect this change, and the chat window is cleared.
8. Improving User Experience
The system is designed with user convenience in mind:
- Real-time updates: Users can see messages in real-time without refreshing the page.
- Simple UI: The interface is clean, minimalistic, and easy to use. It allows for smooth interaction, making it intuitive for users of all levels.
- Keyboard Shortcuts: Users can press 'Enter' to send messages, making the chat flow faster.
9. Future Enhancements
While this system works well for basic communication, several enhancements can be made:
- Authentication: Adding user authentication would allow multiple users to chat securely. Each user could have their unique chat session with the admin or other users.
- Private Messaging: Implementing a private messaging feature where users can chat with each other privately, aside from the public chat.
- Notification System: Sending notifications when a new message is received can improve the real-time experience further.
- Javascript code is both for admin_chat.php
- and user_chat.php is same.
- Check the system chatbox id and input id .if here you can do any mistake the javascript code will not work.
- Check all tagg carefully to integrate the live chat system perfectly.
- Check the onclick element value carefully.It will controlled by jabascript.
- If you miskte any onclick value elements like onclick(messageHeader).javascript cannot identify its in putted command.
- Type carefull css styles coding to design and give smooth performance.
- check ajax attribution carefully.
- check boostrape and javascript cdn inputted in header section carefully or not.if you mistake any cdn it will not work properly.
- check the database creation process like table,column.
How to create a realtime live chat system full tutorial
function fetchMessages() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "fetch_ipd_sms.php", true);
xhr.onload = function () {
if (this.status === 200) {
document.getElementById("messages").innerHTML = this.responseText;
const messagesDiv = document.getElementById("messages");
messagesDiv.scrollTop = messagesDiv.scrollHeight; // Auto-scroll to latest message
}
};
xhr.send();
}
// Set interval to fetch new messages every 2 seconds
setInterval(fetchMessages, 2000);
// Function to send message without reload
function sendMessage() {
const message = document.getElementById("message").value;
if (message.trim() === "") return;
const xhr = new XMLHttpRequest();
xhr.open("POST", "send_message.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function () {
if (this.status === 200) {
document.getElementById("message").value = ''; // Clear input after sending
fetchMessages(); // Fetch new messages after sending
}
};
xhr.send("message=" + encodeURIComponent(message) + "&sender=admin");
}
// Function to delete all messages
function deleteMessages() {
if (confirm("Are you sure you want to delete all messages?")) {
const xhr = new XMLHttpRequest();
xhr.open("POST", "", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function () {
if (this.status === 200) {
document.getElementById("messages").innerHTML = ''; // Clear messages on frontend
}
};
xhr.send("delete=1");
}
}
// Initial call to fetch messages when page loads
fetchMessages();
document.getElementById("message").addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault(); // Prevents the default action of pressing "Enter"
sendMessage();
}
});
Conclusion
Building a real-time chat application using PHP, MySQL, and AJAX is a fantastic way to learn the fundamentals of asynchronous communication and real-time data updates. By leveraging these technologies, you can create a responsive and dynamic user experience without needing advanced technologies like WebSockets.
- Get Medical Report from Hospital Portal Tutorial
- How to Create a Multirole Based Login System
- Patient Invoice Inside Patient Portal Tutorial
- How to Create a Dynamic Login Page
- How to Create an Animated Login Form
- How to Create an Online Doctor Booking Form
- Upload Report Inside the Patient Portal
- How to Install XAMPP Server on PC
- How to Build a Hospital Billing System
- How to Make a Staff ID Card Generating System
- Patient Registration System Tutorial
- How to Build a Staff Dashboard
- Diagram of a Hospital Management System