XML
  Home arrow XML arrow Page 5 - Building an AJAX-Based Chat: Coding the Re...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML

Building an AJAX-Based Chat: Coding the Receiver Module
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 16
    2005-11-15

    Table of Contents:
  • Building an AJAX-Based Chat: Coding the Receiver Module
  • Retrieving messages from the database: defining the “getChatData()” function
  • Building the chat layout: writing the “createMessageBoard()” and “createMessageBox()” functions
  • Registering chat users: defining a simple login page
  • Putting the pieces together: building the whole chat page

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · Over this second article, the "receiver" module of the chat application is properly...
       · This is my first foray into AJAX and DOM, and I this tut was the best place to...
       · Thank you for your compliments on my AJAX tutorial. I'm really glad to know that...
       · Nice articleIsnt it bad pratice to call a function recursively without ever exiting...
       · Thank you for commenting on my article. Comming to your question, recursion can be...
       · Nice article,It would be great if they had a link to an example at the beginning...
       · Thank you for the kind comments on my AJAX tutorial. Of course, when applicable,...
       · Nice article & very interesting, since I have been looking for a thorough, detailed...
       · Hello Rasmus,I'm glad to know that my AJAX chat was what you were looking for....
       · I loved your article. It helped me understand AJAX more. BUT, this does not want...
       · Thank you so much for the kind comments on this tutorial. It's good to see it's been...
       · Nice article. I had just finished my own AJAX chat tutorial when I ran across yours....
       · I'd like to thank you for commenting on my AJAX-based chat tutorial, particulary if...
     

    XML ARTICLES

    - Using Regions with XSL Formatting Objects
    - Using XSL Formatting Objects
    - More Schematron Features
    - Schematron Patterns and Validation
    - Using Schematron
    - Datatypes and More in RELAX NG
    - Providing Options in RELAX NG
    - An Introduction to RELAX NG
    - Path, Predicates, and XQuery
    - Using Predicates with XQuery
    - Navigating Input Documents Using Paths
    - XML Basics
    - Introduction to XPath
    - Simple Web Syndication with RSS 2.0
    - Java UI Design with an IDE







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek