HOME  |  AJAX  |  SOLUTIONS  |  TECHNOLOGIES  |  E-COMMERCE  |  ABOUT US
The JavaScript

Let's start with my favorite piece of AJAX code.
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
document.getElementById('p_status').innerHTML =
'Status: Cound not create XmlHttpRequest Object.' +
'Consider upgrading your browser.'
;
}
}
This code creates the XMLHttpRequest object for the current uses values.  You will see this code written in many different ways in all the different AJAX sites out there. 

A lot of people like to use Try...Catch blocks to check browser compatibility, but I personally think this way looks more professional.  I'm not sure what the best way is, but I've been taught that using Try..Catch blocks leads to sloppy programming (Damn CS purists.).

As you can see, IE suports an ActiveX XMLHttpRequest object, while FireFox, Opera, and the rest use a native object.  If the browser doesn't suport either of these items, we alert the user with our status paragraph.

Now we can use this block of code anywhere we need to create a browser specific XMLHttpRequest object.

Lets create 4 global variables.  We'll add these to the top of the script.
var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
We create two XMLHttpRequest objects, one integer that holds the most recent message that we have recieved (so we don't have to send the whole message list on each request), and a variable that will store our auto refresh time (so we can clear out our setTimout in any function).

Lets add the function to make the call to get the most recent messages.  You can recieve your messages in plain text or XML.  Both have their advantages and disadvantages.  For this AJAX app we will be using XML.
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'getChat.php?chat=1&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
First we check to make sure that our XMLHttpRequest object is ready to send a request.  We should probably add some code here to handle other states, but that is too involved for this section.

The first line:
receiveReq.open("GET", 'getChat.php?chat=1&last=' + lastMessage, true);
Starts the connection to our chat service which will be located at getChat.php along with some data passed as a querystring.  The request type will be a GET.  We could also make the request with a POST as you will see in a minute.

The second like:
receiveReq.onreadystatechange = handleReceiveChat; 
sets what JavaScript function will handle the response from the chat service.  We will create this function in a minute.  Inside this function we will be able to access the data sent back from the server.

The third line sends the request.  Here we pass null because we are doing a GET requets type.  If we were using a POST request, we could pass our parameters here.

Now let's create the function tha will handle the servers response:
//Function for handling the return of chat text
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
var n_messages = message_nodes.length
for (i = 0; i < n_messages; i++) {
var user_node = message_nodes[i].getElementsByTagName("user");
var text_node = message_nodes[i].getElementsByTagName("text");
var time_node = message_nodes[i].getElementsByTagName("time");
chat_div.innerHTML += user_node[0].firstChild.nodeValue + '&nbsp;';
chat_div.innerHTML += '<font class="chat_time">'
chat_div.innerHTML += time_node[0].firstChild.nodeValue + '</font><br />';
chat_div.innerHTML += text_node[0].firstChild.nodeValue + '<br />';
lastMessage = (message_nodes[i].getAttribute('id'));
}
mTimer = setTimeout('getChatText();',2000);
}
There is a lot of stuff going on in this function so let's just take it one line at a time.  The first line:
if (receiveReq.readyState == 4) {
Check to see if the response from the server was good.  We could do error handling here if we would like.

The next line is just setting up a short-cut variable for later use.

The third line creates the XMLDoc object that contains the servers response information.
var xmldoc = receiveReq.responseXML;
 We could also get this data as plain text with receiveReq.response.Text.  Plain text is better when you are returning a single value, but XML is easier for multiple values.  Since we will be returning multiple messages with 4 values each on every request, XML is the way to go.

In order to work with XML responses, you need to understand the XMLDOM.  There can be some tricky little differences between the browsers when working with the XMLDOM.

The next line:
var message_nodes = xmldoc.getElementsByTagName("message"); 
Get's all the messages for this request. Each message node contains multiple pieces of information about the message. Below is an example of how our response XML will look:
<root>
<message id="10">
<user>Ryan Smith</user>
<text>Here is the Message Text</text>
<time>07:53</time>
</message>
</root>
We can have multiple message elements in each response. We pass along the Users Name who posted the message, the message text, and the current time that the message was posted.

The next two lines start the loop through the messages from the response.
var n_messages = message_nodes.length
for (i = 0; i < n_messages; i++) {
For every message we will all the new message to our chat screen.
var user_node = message_nodes[i].getElementsByTagName("user");
var text_node = message_nodes[i].getElementsByTagName("text");
var time_node = message_nodes[i].getElementsByTagName("time");
chat_div.innerHTML += user_node[0].firstChild.nodeValue + '&nbsp;';
chat_div.innerHTML += '<font class="chat_time">'
chat_div.innerHTML += time_node[0].firstChild.nodeValue + '</font><br />';
chat_div.innerHTML += text_node[0].firstChild.nodeValue + '<br />';
The next six lines just update our chat display from the results of the server.
Finally we store the last ID that we recieved from the server so that we can avoid receiving duplicate data.
lastMessage = (message_nodes[i].getAttribute('id'));
After we have updated our display, we will set a timeout to refresh our display.
mTimer = setTimeout('getChatText();',2000);
We will send another request to the server in 2 seconds to see if any new messages have been posted.  We also store it in our global variable so that we can clear it out later.