1. Sending Messages

Building a chat application starts with the ability to send a message from the browser to the server without a full page reload. This is where Ajax comes in — it lets you post data asynchronously while the user stays on the conversation screen.

Writing the Ajax

Use a JavaScript XMLHttpRequest or the simpler fetch API to send the message text to a PHP endpoint. The request should include the message content and any relevant identifiers such as a user or conversation ID. On success, the response can confirm delivery or return the newly stored message.

fetch('send.php', {
  method: 'POST',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: 'message=' + encodeURIComponent(msgText)
})
.then(res => res.text())
.then(data => console.log('Sent:', data));

Writing PHP to Process Data

On the server side, a PHP script receives the Ajax payload, sanitizes the input, and stores the message — typically in a MySQL database. The script should return a meaningful response (JSON or plain text) so the client can update the chat window accordingly.

<?php
$msg = trim($_POST['message'] ?? '');
if ($msg === '') { echo 'empty'; exit; }
// Sanitize and insert into database…
echo 'ok';

2. Setting Up Real-Time Conversation

Once messages can be sent, the next challenge is making the conversation feel live. A common approach is polling: the client periodically requests new messages from the server using Ajax. Each request asks for messages newer than the last received ID, and the PHP script returns only fresh rows.

For a more responsive experience, you can explore long-polling or WebSocket-based solutions, but simple interval polling is a practical starting point that works well with standard PHP hosting.

3. Conclusion

This guide covered the core building blocks of a PHP + Ajax chat application: sending messages asynchronously, processing them on the server, and polling for real-time updates. With these fundamentals in place, you can extend the application with features like user authentication, typing indicators, and message history.

This article was originally published on freetuts.net.