Building an AJAX-Based Chat: Coding the Receiver Module - Retrieving messages from the database: defining the “getChatData()” function
(Page 2 of 5 )
The whole idea for retrieving messages from the database is to request a PHP file that performs a SELECT query for extracting them, and then sends them back to the client for proper display. This entire process is carried out repetitively, at a given time interval. Obviously, the shorter the time interval, the more responsive will be the display of messages. With this concept in mind, here is the recursive definition for the “getChatData()” function:
function getChatData(){
receiverXMLHttpObj.open('GET','getchatdata.php',true);
receiverXMLHttpObj.send(null);
receiverXMLHttpObj.onreadystatechange=
receiverStatusChecker;
setTimeout('getChatData()',5*1000);
}
Even though this function is extremely simple, I believe you will agree that it is remarkably efficient. Essentially, it will fetch the “getchatdata.php” file each five seconds, and all the requests will be handled by the “receiverStatusCheker()” function. As you may guess, the PHP file is tasked with fetching a given number of messages to be displayed on the chat page.
Now, let’s take a look at the “receiverStatusChecker()” function, in order to see how “receiver” requests are properly handled. Below is its source code:
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);
}
}
}
As you can see, the function above handles all the GET requests for getting messages from the server. After the list of messages has been obtained, it will be displayed on the chat page by using the “displayChatData()” function. As you recall, this function was explained in the first part of the series, and since it accepts a requester object as a parameter, it’s used by the respective “sender” and “receiver” objects.
At this point, the chat application is capable of handling independently two requester objects for performing some clearly delineated tasks: retrieving and displaying messages from the server, and inserting new messages into the database each time a user submits a comment. See how the pieces are fitting together in the whole application?
Now that you know how the chat is driven by two independent objects, the next step will be showing the functions that build the basic layout of the chat page. Thus, join me in the next section to find out how this is achieved.
Next: Building the chat layout: writing the “createMessageBoard()” and “createMessageBox()” functions >>
More XML Articles
More By Alejandro Gervasio
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|