To get started with ajax chat demo we need to know some basic javascript functions like javascript recursion, timeout delay and simple php operation to read and write a file.

Ajax chat demo requirements
- A simple index.php page.
- A data.txt file.
- A good mood and some coffee.
I assure you we would be using a single php file with just 60 line of code. Using a back-end mysql database is an advantage but in this demo I am just concentrating on quick functionality by using a data.txt file.
Lets start with structure of Ajax chat demo using html
Create a chat box using div tag with an id in it. Lets make this chat panel look like a shell command box. Add some css to it.
index.php
1 2 3 |
<div id="messagebox" style="background: black; color: white; width: 300px; height: 300px;"></div> |
It looks something like this.

Now we need to create a text box under it using a form where user can enter messages.
1 2 3 4 5 |
<form onsubmit="return sendMessage($('#message').val());"> <input type="text" id="message" style=" width: 300px; border: 1px solid green; height: 42px;"/> </form> |
Here is the screen shot

Write javascript to send messages to server
Here server means index.php file itself. Call jquery api from google hosted apis.
1 2 3 |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> |
Write a function to send messages to server. This function takes the entire message as an argument and pass it to server via ajax.
1 2 3 4 5 6 7 8 9 10 |
function sendMessage(msg) { if(msg === ''){ return false; } $.post("/demo/chat/test.php", {msg: msg}).done(function (response) { }); return false; } |
The form tag above is prevented its default submission by onsubmit = return false. Before it return false function sendMessage perform the post action via ajax to submit the data. Here starts the actual ajax monitoring for new messages every 2 seconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function start(time) { setTimeout(function () { $.get("/demo/chat/test.php", {time: time}).done(function (response) { response = JSON.parse(response); if (parseInt(response[0]) !== parseInt(response[1])) { $("#messagebox").append("<br>" + response[2]); } start(response[0]); }); }, 2000); } |
Finally start the monitoring
1 2 3 |
start(0); |
Write server side code in php to store new messages in a file.
index.php
Get all incoming requests
1 2 3 4 |
$data = isset($_POST["msg"]) ? $_POST["msg"] : ''; $new_message_request = isset($_GET["time"]) ? $_GET["time"] : ''; |
Validate all incoming requests and set exit for each. Exit is necessary so that response is the echo content only not the entire html file. First condition is to store the message coming from ajax request.
1 2 3 4 5 6 7 |
if ($data != '') { $filename = getcwd() . "/data.txt"; file_put_contents($filename, $data); exit; } |
Second condition is to return a response if new messages are there. New messages are recorded only when file time of data.txt is modified.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
if ($new_message_request != '') { $array = array(); $filename = getcwd() . "/data.txt"; $time = filemtime($filename); if ($new_message_request != $time) { $array[0] = $time; $array[1] = $new_message_request; $array[2] = $_SERVER["REMOTE_ADDR"] ." : ". file_get_contents($filename); echo json_encode($array); } else { $array[0] = $time; $array[1] = $new_message_request; $array[2] = $_SERVER["REMOTE_ADDR"] ." : ". file_get_contents($filename); echo json_encode($array); } exit; } |
Explanation (ajax chat demo)
Getting new messages.
We get new messages every 2 seconds if any. The php script receive the new message request as previous time stamp. Then it records the current modified time of data.txt. If times are same then there are no new messages, then it return both the time stamps at $array[0] and $array[1]
But if both the time stamps are different i.e., previous time stamp is changed by new time stamp because new message is there in data.txt file. Hence else part is executed. Returning different file times and new message.
Javascript explanation
In javascript start function is called every 2 seconds. It then compares the two file times, if both are not same then new message is there, appending it to the chat box else previous message is there which isn’t needed to be appended. Find below the complete code for ajax chat demo.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?php $data = isset($_POST["msg"]) ? $_POST["msg"] : ''; $new_message_request = isset($_GET["time"]) ? $_GET["time"] : ''; if ($data != '') { $filename = getcwd() . "/data.txt"; file_put_contents($filename, $data); exit; } if ($new_message_request != '') { $array = array(); $filename = getcwd() . "/data.txt"; $time = filemtime($filename); if ($new_message_request != $time) { $array[0] = $time; $array[1] = $new_message_request; $array[2] = $_SERVER["REMOTE_ADDR"] ." : ". file_get_contents($filename); echo json_encode($array); } else { $array[0] = $time; $array[1] = $new_message_request; $array[2] = $_SERVER["REMOTE_ADDR"] ." : ". file_get_contents($filename); echo json_encode($array); } exit; } ?> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <script> function sendMessage(msg) { if(msg === ''){ return false; } $.post("/demo/chat/test.php", {msg: msg}).done(function (response) { }); return false; } function start(time) { setTimeout(function () { $.get("/demo/chat/test.php", {time: time}).done(function (response) { response = JSON.parse(response); if (parseInt(response[0]) !== parseInt(response[1])) { $("#messagebox").append("<br>" + response[2]); } start(response[0]); }); }, 2000); } start(0); </script> </head> <body> <div id="messagebox" style="background: black; color: white; width: 300px; height: 300px;"> </div> <form onsubmit="return sendMessage($('#message').val());"> <input type="text" id="message" style=" width: 300px; border: 1px solid green; height: 42px;"/> </form> </body> </html> |
You can also add sessions and mysql database to upgrade it. Later on if you need help in customizing a one to one chat system then feel free to contact me.
View live demo here or download the zip here
Thanks for reading.
nice
Thank you
You made some respectable points there. I appeared on the web for the difficulty and found most individuals will go along with with your website.
I discovered your weblog site on google and test just a few of your early posts. Proceed to keep up the excellent operate. I simply extra up your RSS feed to my MSN Information Reader. Seeking forward to studying more from you later on!?
I was more than happy to search out this net-site.I needed to thanks to your time for this glorious read!! I positively enjoying each little little bit of it and I’ve you bookmarked to check out new stuff you weblog post.
A nice step-by-step , well explained example with a working demo. Thanks.
Informative
Nice article with working demo