Today, online chat solutions are witnessing a continuous increase in their popularity across the world. If you’ve used any of the Internet Relay Chat(IRC) clients lately, then you’d be probably well familiar with the overall performance of an online chat service. Even before AJAX was born, online chat solutions had been successful in occupying a unique place in the world of information and technology. It is an AJAX chat applicable which inherits the typical AJAX benefits like cross-platform compatibility and a seamless integration with existing web browser features. One of the greatest advantages of an AJAX chat application is that it avoids the connectivity issues which are common with a range of other web app development technology. Also, an AJAX app exclusively uses HTTP for communication with the web server.
If the above mentioned details about an AJAX chat app appear interesting and you’ve made up your mind for creating one, then you’ve reached the right post. Here, I’ll be offering you a step wise guide on creating a chat room that’s easy to get up and running on every server that runs PHP. There’s no need for any database simply because the chat would get stored inside a text file.
Here’s a look at the pre-requisites of creating a chat room using jQuery and PHP
The technologies that will be used for creating the jQuery and PHP powered chat room include the following:
- PHP – This will handle all the server side-related stuff such as: writing new messages into the text file, reading new messages from the text file, basic security as well as retrieving ‘state’ of text file.
- jQuery/Javascript – This will handle a range of other client-side stuff including the following: asking the server periodically whether any new messages have been posted; scrolling the chat down to the most recent messages; appending new messages to the chat; limiting the textual input in order to prevent any of the ridiculous messages; affirming basic security for the chat room.
- Text file – This will be storing the chat.
Step 1
The basic HTML structure of the chat room will be as shown below:
<div id="chat-wrap"> <h1>Chat Window</h1> <div id="user-name"></div> <div id="chat-box"><div id="chat-row"></div></div> <form id="send-message-area"> <p>Your message: </p> <textarea id="posttext" maxlength="120"></textarea> </form> </div>
The double divs which you see in the above code are just required for pulling off the unnecessary double border effect within the chat area. The textarea with an id as ‘posttext’ along with chat area div.JavaScript will be targeting the two divs.
Step 2
Create a ‘Chat’ function which serves as the parent to a set of other functions which are required for dealing with a lot of other chat-related activities. The code snippet for this function is shown below:
function Chat () { /* call update chat function */ this.update = updateChat; /* call send chat function */ this.send = sendChat; /* call get state function */ this.getState = getState; }
In the above function, updateChat will ask server whether or not there are any new lines in the text file. On finding the same, updateChat will return the lines as JSON and the new lines will be appended to chat. Then, there is sendChat which will be called every time a message is being entered into the text area and ‘return’ is clicked. The above function will pass this data to the server. Next, there is getState which will ask the server about the count of lines included within the current text file. This will enable the function to determine as to when the lines are ‘new’ or ‘old’. All this information is returned in the form of JSON and the related functions are similar to these:
//define get state function function getState() { if(!instanse){ instanse = true; /* define AJAX function */ $.ajax({ type: "POST", url: "ajax.php", data: {'function': 'getState', 'file': file}, dataType: "json", success: function(data) {state = data.state;instanse = false;} }); } } //define update chat function function updateChat() { if(!instanse){ instanse = true; /* define AJAX function */ $.ajax({ type: "POST", url: "ajax.php", data: {'function': 'update','state': state,'file': file}, dataType: "json", success: function(data) { if(data.text){ /* manage data */ for (var i = 0; i < data.text.length; i++) { $('#chat-row').append($(" "+ data.text[i] +" ")); } } /* manage position of current chat */ document.getElementById('chat-row').scrollTop = document.getElementById('chat-row').scrollHeight; instanse = false; state = data.state; } }); } else { setTimeout(updateChat, 1000); } } //define send chat function function sendChat(msg, name) { updateChat(); /* define AJAX function */ $.ajax({ type: "POST", url: "ajax.php", /* manage message */ data: {'function': 'send','message': msg,'nickname': name,'file': file}, dataType: "json", success: function(data){ updateChat(); } }); }
All the above mentioned functions use jQuery’s AJAX abilities and initiate communication using PHP file that’s called ajax.php.
Step 3
Set up a switch statement that covers every possible function
Data that gets passed with AJAX calls is simply an arbitrary value that’s called ‘function’. This values informs the PHP file about the kind of task it needs to perform. So, it is essential to set up a switch statement that would cover every possible function. On calling getState, the text file will be read and number of lines will be returned as the output. On updating, the same text file will be read and any new lines will be returned. On sending, the message will be processed, followed by getting written into text file in the form of a new line.
The PHP for the same is displayed below:
<?php $function = $_POST['function']; $log = array(); switch($function) { /* get state case */ case('getState'): /* check file available or not */ if (file_exists('data.txt')) { /* assign to variable */ $lines = file('data.txt'); } $log['state'] = count($lines); break; /* update case */ case('update'): $state = $_POST['state']; /* check file available or not */ if (file_exists('data.txt')) { /* assign to variable */ $lines = file('data.txt'); } $count = count($lines); if ($state == $count){ /* if state & count are equal */ $log['state'] = $state; $log['text'] = false; } else { /* if state & count are no equal */ $text= array(); $log['state'] = $state + count($lines) - $state; foreach ($lines as $line_num => $line) { if ($line_num >= $state){ $text[] = $line = str_replace("\n", "", $line); } } $log['text'] = $text; } break; /* send case */ case('send'): $nickname = htmlentities(strip_tags($_POST['nickname'])); $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; $message = htmlentities(strip_tags($_POST['message'])); if (($message) != "\n") { if (preg_match($reg_exUrl, $message, $url)) { $message = preg_replace($reg_exUrl, '<a href="'.$url[0].'" target="_blank">'.$url[0].'</a>', $message); } fwrite(fopen('data.txt', 'a'), "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n"); } break; } echo json_encode($log);
Step 4 – Get the chat room started
Now, you’ll be required to write some Javascript code for loading jQuery and create some quick functions for gathering chat participants name for joining the chat room. Here is the Javascript associated with this step:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="demo.js"></script> <script> // open popup prompt for ask name of user var name = prompt("Enter your name:", "Guest"); // default name is 'Guest' if (!name || name === ' ') { name = "Guest"; } // strip tags name = name.replace(/(<([^>]+)>)/ig,""); // display name on page $("#user-name").html("User: <strong>" + name + "</strong>"); var chat = new Chat(); $(function() { chat.getState(); /* define function when key presses */ $("#posttext").keydown(function(event) { var key = event.which; /* if key including return. */ if (key >= 33) { var maxLength = $(this).attr("maxlength"); var length = this.value.length; /* define limit of new content */ if (length >= maxLength) { event.preventDefault(); } } }); /* define function when key release */ $('#posttext').keyup(function(e) { if (e.keyCode == 13) { var text = $(this).val(); var maxLength = $(this).attr("maxlength"); var length = text.length; // send if (length <= maxLength + 1) { chat.send(text, name); $(this).val(""); } else { $(this).val(text.substring(0, maxLength)); } } }); }); </script>
Bonus Tip
Now that you’re done with starting your chat room, you can call the ‘update’ function regularly for checking any new messages. For this, you can use Javascript’s setInterval() function as shown below:
<body onload="setInterval('chat.update()', 1000)">
That’s it!
Conclusion
Building a unique chat room using jQuery and PHP is indeed an excellent business decision. I’m sure this post of mine would have rendered you excellent insights on proceeding ahead with the same in utmost comfortable manner.
Leave a Reply