In this blog post, we’ll walk through building a simple real-time chat application using AJAX. Real-time chat applications are commonly used for customer support, social media interactions, and live event discussions. We’ll use AJAX for asynchronous updates to simulate real-time interactions, making our chat app responsive without page reloads.
Step 1: Setting Up the HTML Structure
Start by creating the HTML layout for the chat application. Our structure will include a chat display area, an input box for typing messages, and a submit button to send messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Chat Application</title>
<style>
/* Basic styling for the chat container */
#chatContainer { width: 400px; margin: 20px auto; border: 1px solid #ccc; padding: 10px; }
#chatDisplay { height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; }
#messageInput { width: calc(100% - 80px); padding: 5px; }
#sendButton { width: 70px; }
</style>
</head>
<body>
<div id="chatContainer">
<div id="chatDisplay"></div>
<input type="text" id="messageInput" placeholder="Type a message">
<button id="sendButton">Send</button>
</div>
</body>
</html>
#chatDisplay
: This is where all chat messages will be displayed.
#messageInput
: The input field where users type their messages.
#sendButton
: A button to send the typed message.
Step 2: Setting Up the Backend (PHP)
We’ll create two PHP scripts: one to handle sending messages and another to retrieve messages.
1. send_message.php
– To Save Messages
<?php
// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=chat_app', 'username', 'password');
// Insert message into the database
if (isset($_POST['message'])) {
$message = $_POST['message'];
$stmt = $pdo->prepare("INSERT INTO messages (message) VALUES (:message)");
$stmt->execute([':message' => $message]);
}
?>
2. fetch_messages.php
– To Fetch Messages
<?php
// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=chat_app', 'username', 'password');
// Retrieve all messages
$stmt = $pdo->query("SELECT * FROM messages ORDER BY id ASC");
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($messages as $msg) {
echo "<p>" . htmlspecialchars($msg['message']) . "</p>";
}
?>
Database Setup: Create a messages
table in your database with columns id
(INT, auto-increment) and message
(TEXT).
Step 3: Adding JavaScript for AJAX Requests
Now, we’ll use AJAX to send and retrieve messages without reloading the page. We’ll use setInterval
to fetch new messages every few seconds.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// Function to fetch messages
function fetchMessages() {
$.ajax({
url: 'fetch_messages.php',
success: function(data) {
$('#chatDisplay').html(data);
$('#chatDisplay').scrollTop($('#chatDisplay')[0].scrollHeight); // Auto-scroll to bottom
}
});
}
// Call fetchMessages every 2 seconds
setInterval(fetchMessages, 2000);
// Function to send a new message
$('#sendButton').on('click', function() {
var message = $('#messageInput').val();
if (message.trim() !== '') {
$.ajax({
url: 'send_message.php',
type: 'POST',
data: { message: message },
success: function() {
$('#messageInput').val(''); // Clear input
fetchMessages(); // Update messages immediately
}
});
}
});
// Send message on Enter key press
$('#messageInput').on('keypress', function(e) {
if (e.which === 13) { // Enter key code
$('#sendButton').click();
}
});
</script>
fetchMessages
function: Retrieves new messages every 2 seconds and updates the #chatDisplay
area. The scrollTop
method ensures the display auto-scrolls to the latest message.
- Sending Messages: The click event on
#sendButton
sends the message in #messageInput
to the server. If the Enter key is pressed in the input field, it also triggers the send function.
Step 4: Testing the Chat Application
- Set Up Your Database: Make sure you have a
messages
table in your database.
- Run the Application: Open the HTML file in a browser and try sending messages. Open another browser tab to see the real-time effect.
Step 5: Enhancing the Application
For a production-ready chat application, consider the following enhancements:
- User Identification: Add user names and store them along with messages in the database.
- Timestamp: Add timestamps to messages to show when each message was sent.
- Styling and UX: Improve the appearance of the chat interface and add visual indicators like "User is typing..."
Conclusion
With AJAX, we’ve created a simple yet effective real-time chat application without needing to refresh the page. Although this approach is suitable for small applications, consider using WebSockets (like Pusher or Laravel Echo) for larger applications requiring truly instant updates.
This example introduces the core concepts, and you can build upon it to add more advanced features as needed.