Building an AJAX-Based Chat: Coding the Receiver Module
In this second part of a three part series of articles, you will learn a lot more material related to building the AJAX-based chat. You will discover how two requester objects fetch or add new messages to the database. Also, you will see the code for a simple login page for registering users that want to access the chat page.
Building an AJAX-Based Chat: Coding the Receiver Module - Putting the pieces together: building the whole chat page (Page 5 of 5 )
As I mentioned before, below is the complete code for the chat page, along with the PHP snippet that fetches the nicknames previously registered on the login page:
<?php // get user name session_start(); $user=$_SESSION['user']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"> <html> <head> <title>AJAX-BASED CHAT SYSTEM</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style type="text/css"> body { margin: 0; padding: 0; } p { font: normal 14px Arial, Helvetica, sans- serif; color: #000; margin-bottom: -12px; } span { margin-left: 20px; font: bold 12px Verdana, Arial, Helvetica, sans-serif; color: #003399; } form { display: inline; } .msgfield { font: normal 14px Arial, Helvetica, sans- serif; color: #000; width: 400px; } div#messages { height: 450px; background: #d9dcea; padding: 10px 0px 10px 2px; border: 1px solid #000; } div#messagebox { background: #ccf; border-left: 1px solid #000; border-right: 1px solid #000; border-bottom: 1px solid #000; padding: 10px; } </style> <script language="javascript"> /* ********************************************* AJAX-Based Chat System Author: Alejandro Gervasio Version: 1.0 ********************************************* */ // getXMLHttpRequest object function getXMLHttpRequestObject(){ var xmlobj; // check for existing requests if(xmlobj!=null&&xmlobj.readyState! =0&&xmlobj.readyState!=4){ xmlobj.abort(); } try{ // instantiate object for Mozilla, Nestcape, etc. xmlobj=new XMLHttpRequest(); } catch(e){ try{ // instantiate object for Internet Explorer xmlobj=new ActiveXObject ('Microsoft.XMLHTTP'); } catch(e){ // Ajax is not supported by the browser xmlobj=null; return false; } } return xmlobj; } // check status of sender object function senderStatusChecker(){ // check if request is completed if(senderXMLHttpObj.readyState==4){ if(senderXMLHttpObj.status==200){ // if status == 200 display chat data displayChatData(senderXMLHttpObj); } else{ alert('Failed to get response :'+ senderXMLHttpObj.statusText); } } } // check status of receiver object function receiverStatusChecker(){ // if request is completed if(receiverXMLHttpObj.readyState==4){ if(receiverXMLHttpObj.status==200){ // if status == 200 display chat data displayChatData(receiverXMLHttpObj); } else{ alert('Failed to get response :'+ receiverXMLHttpObj.statusText); } } } // get messages from database each 5 seconds function getChatData(){ receiverXMLHttpObj.open('GET','getchatdata.php',true); receiverXMLHttpObj.send(null); receiverXMLHttpObj.onreadystatechange= receiverStatusChecker; setTimeout('getChatData()',5*1000); } // display messages function displayChatData(reqObj){ // remove previous messages var mdiv=document.getElementById ('messages'); if(!mdiv){return}; mdiv.innerHTML=''; var messages=reqObj.responseText.split ('|'); // display messages for(var i=0;i<messages.length;i++){ var p=document.createElement('p'); p.appendChild(document.createTextNode (messages[(messages.length-1)-i])); mdiv.appendChild(p); } } // send user message function sendMessage(){ var user='<?php echo $user?>'; var message=document.getElementsByTagName ('form')[0].elements[0].value; if(message.length>100){message=message.substring(0,100)}; // open socket connection senderXMLHttpObj.open('POST','sendchatdata.php',true); // set form http header senderXMLHttpObj.setRequestHeader('Content- Type','application/x-www-form-urlencoded'); senderXMLHttpObj.send('user='+user+'&message='+message); senderXMLHttpObj.onreadystatechange= senderStatusChecker; } // create messages board function createMessageBoard(){ var mdiv=document.createElement('div'); mdiv.setAttribute('id','messages'); document.getElementsByTagName('body') [0].appendChild(mdiv); } // create message input box function createMessageBox(){ // create message box container var mdiv=document.createElement('div'); mdiv.setAttribute('id','messagebox'); // create message form var mform=document.createElement('form'); // create message box var mbox=document.createElement('input'); mbox.setAttribute('type','text'); mbox.setAttribute('name','message'); mbox.className='msgfield'; // create 'send' button var mbutton=document.createElement ('input'); mbutton.setAttribute('type','button'); mbutton.setAttribute('value','Send'); mbutton.onclick=sendMessage; // create login text var sp=document.createElement('span'); sp.appendChild(document.createTextNode ('Logged in as: <?php echo $user?>')); // append elements mform.appendChild(mbox); mform.appendChild(mbutton); mform.appendChild(sp); mdiv.appendChild(mform); document.getElementsByTagName('body') [0].appendChild(mdiv); mbox.focus(); mbox.onfocus=function(){this.value='';} } // initialize chat function intitializeChat(){ if(document.getElementById&&document. getElementsByTagName&&document.createElement){ createMessageBoard(); createMessageBox(); getChatData(); } } // instantiate sender XMLHttpRequest object var senderXMLHttpObj=getXMLHttpRequestObject(); // instantiate receiver XMLHttpRequest object var receiverXMLHttpObj=getXMLHttpRequestObject (); // initialize chat window.onload=intitializeChat; </script> </head> <body> </body> </html>
As I expressed earlier, above is the whole source code for the chat web page. Notice how the “initializeChat()” function is called when the page is loaded, in order to create the page layout, as well as how the two requester objects are instantiated right at the end of the script. The one new snippet added to the whole page is the PHP code that populates the “user” variable with the value stored in $_SESSION[‘user’]. This little trick makes easy to obtain the nickname entered by the user, for inserting into the database table along with the newly submitted messages.
At this point, the chat application is near completion. Of course, if you enjoy a challenge, you might want to try to figure out on your own how the server processing is done, in order to fetch and insert new messages into the database. Whether you accept the coding challenge or not, over the third (and last) part of this series, I’ll be writing down the PHP files that process user messages and interact with the MySQL database.
Wrapping up
Over this second tutorial, you’ve learned a lot more precious material related to building the AJAX-based chat. Hopefully, you’ve understood how the two requester objects do their business, either for fetching or adding new messages to the database. Also, I’ve coded a simple login page for registering users that want to access the chat page. What’s next, though? I’ll conclude this series by writing the server-side code that queries the database and handles chat messages. Until the last part, stay tuned!
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.