The PHP live chat is mostly of web-based, AJAX-based. We propose a concise example of client-server structure about a jQuery or JavaScript chat room. And no database is required here. So far, one chat room is provided for unlimited attendees. In next post, we are going to extend it to multiple chat rooms, thus to category chatting people.
All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.
Estimated reading time: 8 minutes
EXPLORE THIS ARTICLE
TABLE OF CONTENTS
BONUS
Source Code Download
We have released it under the MIT license, so feel free to use it in your own project or your school homework.
Download Guideline
- Prepare HTTP server such as XAMPP or WAMP in your windows environment.
- Download and unzip into a folder that http server can access.
SECTION 1
Single Chat Room
HTTP chat rooms allow group people to pass messages to each other using browsers. PHP scripts on server sites handle activities and contents in chat rooms. On the other hand, Javascript AJAX offers proper interactions in a room for people to chat.
Client-Server Architecture
Let us begin with a single live chat room in PHP AJAX. For multiple chat rooms, the next article will mention additional stuff about it. We interpret chat rooms from the view of client-server.
One of the mostly used HTTP services is Apache. It listens incoming chat sessions from browsers. The sessions are in a form of AJAX request. Each Apache child process serves the chat request by updating chat contents in a log file, and then reply with up-to-date contents.
Seriously, if two sessions come in at the same time as the red circles indicate, multiple accesses to the log file could make data inaccurate. There should be a secure mechanism called Exclusive Lock for protection.
Where to Keep Chat Contents?
The answer is back-end. A chat log records what people chat for a single PHP AJAX live chat room. PHP scripts in servers receive new lines of message, and would be in charge of keeping chat contents up-to-date.
Front-end chat interfaces push a new content, and pull complete contents of a chat room.
Multiple Chat Rooms
Primarily, each chat log represents the storage for each chat room. To allocate spaces for more than one group, we want multiple chat rooms. At this time, server sites should manage each room and its chat contents.
SECTION 2
Chat Room Layout
The keys to JavaScript chat room layout are about attendees and the contents stored by PHP scripts. The name of attendee should be clearly presented. While the contents could be massive, so displaying panel should be scrollable and automatically anchor to the right position.
Using jQuery Mobile
Truly, using jQuery Mobile is more friendly on mobile devices. But you do consider the versions of jQuery and jQuery Mobile compatible. Here are the versions we choose.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
Chat Room Layout
When coming to a chat room, a prompt box will ask your chat name. Everybody gives a name to start group chatting. Duplicated names are possible, because we don’t check identity here.
The following jQuery Mobile Page widget helps us build the chat room layout in ease. The chat content block <div id="chat"></div>
is empty in HTML codes, because servers will dynamically fill the up-to-date data.
<div data-role="page" style="background:#40E0D0;">
<div data-role="header">
<p class="text-center">LIVE CHAT - Single Room</p>
</div>
<div data-role="content">
<div class="main-content">
<p>Your Name: <span id="name" class="nickname"></span></p>
<div id="chat"></div>
<br>
<input type="text" data-clear-btn="true" id="msg">
</div>
</div>
</div>
Chat Room Scrolling
In particular, the CSS portion overflow:auto
contributes to the appearance of scroll bar. The JavaScript chat room will be vivid if contents can be scrolled up or down. Moreover, in jQuery Mobile, changing CSS attributes should be done by !important such as color: maroon!important
.
.main-content { margin:0% 5%; font-size: 1em; text-shadow: none; }
.nickname { background: #6495ED; color:white; border-radius: 5px; padding: 2px 6px; }
.text-center { text-align: center; }
#chat { padding:0 10px; height:350px; overflow:auto; background:white; border-radius: 5px; }
#msg { color: maroon!important; }
SECTION 3
Chat Room Actions
We have Send and Poll actions to do. The former pushes new messages, and pull latest chat contents. The latter pulls up-to-date contents and anchor content positions to show.
Action: send()
We have two essential functions, send()
and poll()
. The function send()
push new messages to server sites, and pull newly updated chat contents down.
When you completely key in sentences, there is no sending button to click. By handling the event keyup
, people just press <Enter> habitually to push messages up.
$(document).ready(function() {
chatname = prompt("Enter your chat name:", "Guest");
if(chatname == null) { chatname = "Guest"; }
$("#name").text(chatname);
poll();
});
$('#msg').on("keyup", function(e) {
if (e.keyCode == 13) send();
});
In AJAX callback function, the jQuery codes $("#chat").html(r)
displays up-to-date chat contents for people.
Next, how to scroll to the bottom? It is necessary for attendees to see what words they just enter. These codes can do it.
.scrollTop($('#chat')[0].scrollHeight)
That is a tricky method, so just remember the formula, but ignore inspecting the details.
function send() {
$.ajax({
url: "ajax-server.php",
type: "POST",
data: { action: "send", name: $("#name").text(), msg: $("#msg").val() },
success: function(r) {
$("#chat").html(r).scrollTop($('#chat')[0].scrollHeight);
$("#msg").val("");
},
});
}
Action: poll()
The function poll()
pull up-to-date chat contents. For group attendees not keying in sentences, a series of periodical requests get newly updated data down. So you can find the code setTimeout(poll, 1000)
, which sets repeated interval to be 1000 milliseconds or 1 second.
function poll() {
$.ajax({
url: "ajax-server.php",
type: "POST",
data: { action: "poll" },
success: function(r) {
$("#chat").html(r);
},
});
setTimeout(poll, 1000);
}
SECTION 4
Back-End Jobs
Finally, let us look at PHP AJAX live chat scripts in server sites. We don’t want to manage rooms, because there is only 1 chat room, and 1 set of chat contents in a file. But what is the format of chat logs? HTML should be a good candidate.
Handling Send Action
If new words come to servers, PHP scripts write 3 kinds of data into chat logs. There are time, chat name, and new messages. The format of chat logs is HTML, and we highlight only the chat name by a CSS class. Once updated, reply to browser clients with new HTML contents.
<p>07:14 <span class='nickname'>Michael</span> I join the discussion.</p>
<p>07:15 <span class='nickname'>Lisa</span> Hello, Michael. Where is Steve?</p>
<p>07:15 <span class='nickname'>Steve</span> I am here.</p>
<p>07:17 <span class='nickname'>Michael</span> Let's go camping this week. How about?</p>
<p>07:22 <span class='nickname'>Steve</span> It sounds good. But I don't have camping tents. The tents are perhaps very expensive.</p>
<p>07:24 <span class='nickname'>Lisa</span> Don't worry about it. I can borrow two tents from my brother.</p>
<p>07:32 <span class='nickname'>Steve</span> Michael, do you have camping stove?</p>
<p>07:33 <span class='nickname'>Michael</span> Sure, I have one. That is enough for us.</p>
Don’t forget the collision conditions may happen, suppose that massive people gather in a chat room. The option LOCK_EX
forces the exclusive locking between multiple accesses to a single file.
<?php
$chatfile = "chat.log";
switch($_POST["action"]) {
case "send":
$format = "<p>%s <span class='nickname'>%s</span> %s</p>";
$str = sprintf($format, date("H:i"), $_POST["name"], $_POST["msg"]);
file_put_contents($chatfile, "$str\n", FILE_APPEND | LOCK_EX);
echo chatLog($chatfile);
break;
case "poll":
echo chatLog($chatfile);
break;
}
function chatLog($f) {
if(file_exists($f)) $log = file_get_contents($f); else $log = "";
return $log;
}
?>
Handling Poll Action
Each chat room of attendees wants to refresh repeatedly, so that they can get new messages from each other in the group. The back-end site just responses to browser clients the up-to-date contents of chat room.
FINAL
Conclusion
Wish the concise HTTP-based example giving you a tutorial of chat room coding in PHP AJAX. Next, we will propose another example for multiple chat rooms soon.
Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!
Suggested Reading
- How to Create Many Web Chat Rooms Using PHP, JS
- 6 Stages of Registration Form in PHP with Email Check
TRY IT
Quick Experience
That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.
Try It Yourself
Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.