Part 1 of AJAX Demystified we discussed what is AJAX and gave a high level overview of how it all works.
Part 2 we discussed in more detail on how to use the xmlhttprequest object and how to dynamically load content onto the web page without the round trip. Part 3 we’ll get into some more detail that will give you a really good understanding on AJAX and its plumbing.
Opening the Request Object
The next line takes a bit of understanding. It takes three (3) arguments and depending on the arguments the outcome can vary greatly.
Open method Argument #1
. open(“GET”, sUrl, true);
Available input: GET or POST
Type: string
The first argument takes a string. It can be either “GET” or “POST”. A “POST” is usually used when you’re sending the server data such as a form submit. Since we’re not sending any data, it’s easier to use “GET”.
Open method Argument #2
.open(“GET”, sUrl, true);
Available input: a valid URL to the server page
Type: string
The second argument is the URL where to send the request. This is also a string. However it’s easier to create a variable beforehand with the sUrl variable. If the URL is not valid or it’s not pointing to the right location, the call will fail.
Our example we’re sending the request to a PHP page. However, we could have sent the request to any page that your server can understand. We could have used an asp.net page just as easily.
Open method Argument #3
.open(“GET”, sUrl, true);
Available input: true or false
Type: Boolean
The last argument tells the browser if we are sending the information asynchronously or not. If it’s set as true, then it’s set asynchronously. If it’s set to false, then the call is synchronous and will wait until the server returns with the response.
You may be asking yourself “why would I ever make a synchronous call?” There are several times where you don’t want the user to continue to use the application until the call is returned such as if the user submitted a transaction type of call. For example what if the page was allowing the user to submit an order? We would want to wait for the response before allowing them to continue.
Setting the Ready State of the Request Object
The next line is vital to making an asynchronous call.
requestObj.onreadystatechange = updateDateTime;
The onreadystatechange property needs to know what client side JavaScript function to call returning the response data from the server. This is the callback function. Without it we would have to wait until the response comes back from the server to continue. Remember the third argument of the open method needs to be set to true for this to properly work.
It’s vital that the onreadystatechange property is set before calling the send method of the request object. If not, the callback function can’t be called since the request object did not know until it was too late.
The last thing to remember is not to add the parentheses at the end of the function name when setting it to the onreadystatechange property. In JavaScript the updateDateTime would look like so:
function updateDateTime()
{
…
…
}
Sending the Request to the Server
The request object has been initialized, opened, set with what it needs to do, where to go get the information and what callback function to return the response. Now all that is left is to send the request.
requestObj.send(null);
Ok that seems simple enough but why are we sending a null? The reason is we are not sending any information to the server. The default then is to pass in a null object. A null is an empty value. We are sending nothing to the server because we are not required to pass any information.
The key to remember is that AJAX sends information to the server asynchronously and does not use the traditional form submit as we’ve done in the past. When the send method is called the user can continue working on the site. (However more than likely you should get a response almost instantly)
Nonetheless, if you’re having the server do a complex task that may take time, they are free to do other things with the page while waiting for the response back from the server. When the server is ready to send back the response, it makes the call to the callback function we setup with the onreadystatechange property of the request object.
HTML: Calling the request method
<BODY>
<H1>Get The Server’s Date and Time</H1>
<a href=”javascript: getServerDateTime()”>Make AJAX Call</a>
</BODY>
This is a very simple HTML body. All we have here is a header telling the user what the page is doing and a hyperlink.
One thing that you will notice with the hyperlink is that we are making a JavaScript call. It’s calling our AJAX function that will make a request to the server to get the server’s date and time.
We could have used a button or even a timer to go get the time of the server every X seconds. It doesn’t matter. However, notice that we are NOT using a form tag with a submit button. The JavaScript and the request object will handle all the request/response features that normally would have been done with the form tag.
HTML: Place holder for the Response from the server
<BODY>
<H1>Get The Server’s Date and Time</H1>
<a href=”javascript: getServerDateTime()”>Make AJAX Call</a>
</br>
<div id=”divDateTime”></div>
</BODY>
We added two (2) more lines of HTML. The first is a line break so that we have a space. The other is a div tag with an id of divDateTime. Notice that we have nothing in between the start and end of the div tag. We could have any text in there if we wanted to. When the server returns the current date and time, the date will be inserted between the start and end tags of divDateTime.
This is how we can update the HTML dynamically. Instead of a round trip with the entire HTML sent back again, only the server’s date will be sent. The browser’s callback function (that we set with the onreadystatechange property of the request object) is responsible for finding this tag and entering in the response from the server.
Server Side Code
<?php
$today =date(’l dS \of F Y h:i:s A’);
echo $today
?>
The PHP code above has a very simple task. It creates a date string and returns the response. Instead of sending back HTML like a PHP page normally would do, it sends back a fully formatted date.
If today’s date is Feb 22nd, 2007, it will return back Monday 22nd of February 2007 10:05 AM.
The PHP code could have been complex call like going to the database and retrieving information and then sending back a snippet of XML or HTML. We used this minimal snippet of code to show that it does not always have to be HTML or XML that it returns.
Handling the Callback function (Server’s Response)
After the server has completed receiving the request and is ready to return back a response, the callback function set up with the onreadystatechange property is called. The web browser handles this. It knows that the request object made the call and what function to call based on the callback that was setup.
function updateTime()
{
if (requestObj.readyState == 4)
{
var sNewServerDateTime = requestObj.responseText;
var elDivDateTime = document.getElementById(“divDateTime”);
elDivDateTime.innerHTML = “The Server’s current time is:” +sNewServerDateTime;
}
}
Request readyState Property
Available output:
0 = Object not initialized
1 = Loading
2 = Loaded
3 = Interactive
4 = Complete
Type: Integer
The readyState property can be used to get the current state of the Request object. The return value that is important in the callback function is the value 4. The property returns that the request object has completed and we should be able to retrieve the response text returned from the server.
Request responseText Method
Available output: The response from the server
Type: String
Even though the readyState property has been set to Complete (4), we should have checked the status of the request object. If there was a problem the code should handle it. However for this sample we’re just going to assume that it worked.
(BTW you should never assume anything when writing real software! The only thing you should assume is that it could fail and should always check the state of any object you use)
If all is good we should have received the Date and Time Stamp value from the server. However this could have been a full set of HTML, XML or any data we wished to be returned to the user’s browser.
Document getElementById Method
This method is used to find an Element by its Id. We are looking for the element with the Id of “divDateTime”. If it’s found, we have a reference to the element.
innerHTML Method
The innerHTML method allows you to change the inner HTML of an element. We used the getElementById to find the div tag that we will use to dynamically show the server’s date and Time. This allows us to change the HTML of the page without reloading the entire page. Of course this was a very simple update, but it could have easily have been an entire HTML table of information.
Conclusion
The sample is very simple but it does show how easy it is to make an AJAX call and update the web page without having to update the entire page. Now that you have a better understanding of how AJAX works, you’ll have a good foundation to build upon
Check out the original PDF article I wrote over at Venice Consulting Group’s website.