AJAX Demystified Part 3 of 3

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.

AJAX Demystified Part 2 of 3

Part 1 of AJAX Demystified we discussed what is AJAX and gave a high level overview of how it all works.

Part 2 we are going to get into more detail and actually show you some examples of how it all works.

No more reloading the page!
Let’s say we have a site that contains a list of all clients. We may have a search page that uses AJAX to select the clients from the list.

When the company name is entered we don’t want to reload the entire web page again. Instead we will make an AJAX call to retrieve the clients that match the search criteria. When the request comes back from the server, instead of reloading the page again, we only render the results under the search input area.

The way this all works is by updating the content of placed div tags within the HTML. We’ll get into the details in a second.
This image shows before the call is made and where we have the div tag placed

And after the callback is made back to the page:

AJAX: Do it yourself (DIY)

OK enough you say. Show us how to make an AJAX Call. That sounds fair. You could use one of the frameworks available, but I think to truly understand AJAX, you need to at least understand how to do it yourself without using a framework. Once you feel comfortable with this, I do suggest using one of the frameworks because the “heavy lifting” will be handled for you. By understanding the core of AJAX, I believe you will be less likely to make big mistakes with an AJAX framework.
There are a couple of things that I won’t cover while explaining how to use AJAX:
HTML: If you don’t understand the basics of HTML, this will be beyond your expertise. I would recommend getting a good handle of HTML first. I would recommend the Visual Start Guide.
JavaScript: I don’t expect you to be an expert, but you need to know some of the basics of the scripting language.
Document Object Model (DOM): I won’t go much into the DOM, but I will be using some of the DOM to find Elements of the HTML.
Server side Development. The example will use PHP for the server side. I will try to explain what is going on the back end. It’s not necessary to understand PHP, but if you’ve done any server side development, you’ll probably understand what is going on.

The Request Object (XMLHTTPRequest) – The core object of AJAX

Most modern browsers have the ability to do AJAX development through the request object. Without the request object we’re not able to do AJAX development. This request object is responsible for the calls between the browser and the server.
On the other hand I wish life was that simple. The JavaScript function will need to determine which version to use. Internet Explorer 6 requires the ActiveX request object, but the other browsers don’t understand ActiveX, so they require making use of XMLHTTPRequest object. The good news is that JavaScript has a nice feature: the try…catch exception handling commands. If the browser fails trying to create one, we can try initializing the request object with another call.
NOTE:
The actual name of the object is XMLHTTPRequest. To keep it simple I am going to call it the request object. This refers to the XMLHTTPRequest object in FireFox, Safari and Opera. If the browser is Microsoft’s Internet Explorer, then I am referring to the Msxml2.XMLHTTP or the Microsoft.XMLHTTP ActiveX Controls.
For this example let’s start by inserting some JavaScript into a normal HTML page. We’re going to create a JavaScript function called initRequest(). Add this in the HEAD Tag of the HTML
<head>
<title>My First AJAX App</title>
<script>
var requestObj = null;
function initRequest ()
{
try
{
requestObj = new XMLHttpRequest();
}
catch (failedNoramlRequest)
{
try
{
requestObj = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (tryotherObject)
{
try
{
requestObj = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (failed)
{
requestObj = null;
}
}
}
if (requestObj == null)
alert(“You’re browser does not support AJAX!”);
}
</script>
</head>
The first variable that is created is the request object outside of the function. This is a global variable. It’s global because we’ll be using the same object when receiving data back from the server in a different function. The function needs to initialize the request object. The correct XMLHttpRequest object needs to be initialized based on the user’s browser they are using.
If an exception is thrown, the code checks to see if it can use the Msxml2.XMLHTTP ActiveX control from Microsoft. (This object only works on Microsoft browsers running on Microsoft Windows) If that fails, then our last resort is to try the older Microsoft.XMLHTTP object.
Finally if the last exception is thrown, the user is out of luck! On the other hand this will be VERY unlikely. Their browser would have been several years old and probably could not use most of the websites created today. One solution you could offer is the ability to redirect them to the Molliza or Microsoft website to download the latest browser.

Calling the Request Object

Now that the function has created the Request object, it’s time to try it out and make a request to the server. Let’s start by creating a new JavaScript function that we will call from a hyperlink. Add the following code after the initRequest() function: (make sure it’s still within the script tag of the HTML Page.)
function getServerDateTime()
{
initRequest();
if (requestObj != null)
{
var sUrl = “ajax_getServerDateTime.php”;
requestObj.open(“GET”,sUrl,true);
requestObj.onreadystatechange = updateDateTime;
requestObj.send(null);
}
}
The first line in the function takes care of creating the new Request object.
If the request object is not null then the request object can be used. Next a variable is created that contains the URL string. The URL must point to the server page that will be receiving the request from the browser.
This concludes Part 2.
Part 3 wraps up our series on Ajax Demystified.

AJAX Demystified Part 1 of 3

What is AJAX?

If you think that AJAX is a cleaning product then you your reading the wrong article and you should stop immediately. However if the people you talk to on a regular basis keep using words like AJAX and web 2.0, then this article is for you.

The acronym AJAX stands for Asynchronous JavaScript And (+) XML.

OK…. But what does AJAX really mean?

AJAX has been described as way to build rich/dynamic Internet applications that are interactive and responsive. Rich and dynamic Web Sites and Internet Applications typically have one thing in common – they are heavy. Heavy in the sense that that entire rich content means larger downloads and slower performance for the end user. So, how does AJAX help to make sites more responsive? One of the primary ways is to render the page once and then update sections of the page without having to reload the entire page again. So now, with AJAX, every time a content element changes, we no longer have to reload the entire page, just that particular piece of content.

Where did the catch-phrase “AJAX” come from?

Back in early 2005, Jesse James Garrett came up with acronym AJAX. Looking back this is not the best acronym for the technology described but the Internet community adopted it and the rest is history. The irony of it all is Jesse did not mean for it be an acronym.

Do I have to know or use JavaScript to develop an AJAX App?

The short answer is no. There are many AJAX enabled languages/frameworks that require the developer to use little or no JavaScript. A few popular frameworks include Ruby on Rails, Microsoft’s ASP.NET AJAX 1.0, Sun’s Java and Adobe Flash. Each requires little or no knowledge of JavaScript to build an AJAX enabled web app. Most of the frameworks listed above create the JavaScript for you.

Nevertheless, if you don’t want to use a specific framework on the back end, then doing your own AJAX implementation gives you the greatest flexibility. The other possibility is to use a JavaScript framework that supports AJAX, one of the most popular being Prototype JS. In fact Ruby on Rails has integrated Prototype directly into its own framework. In our experience, using the Prototype framework still gives you the greatest flexibility without locking you to specific back end framework.

Do I have to use XML?

The XML part of AJAX acronym can be the most confusing part. At times you will use XML to send and receive data between the browser and the server, however most of the time you’ll probably be receiving HTML content and using the DOM (document object model) to update a specific section of the page. Don’t feel guilty if you’re not using XML, it’s not a requirement. This is another reason why AJAX is probably not the best name to describe the technology. You could create an entire AJAX enabled site and NEVER use XML!

Before AJAX we had the Postback! (Rinse and repeat)

Before AJAX enabled web applications, the process was simple:

A User’s browser makes a request to the Website.

The server receives the request.

The server processes the request and resends back the entire page.

A User’s browser receives the request and renders the HTML.

User enters some data, clicks a button or hyperlink and then sends the request back to the server.

Repeat the process.

However, there are a couple of problems with this approach:

The server is doing all the work. The server is sending the entire HTML of the page each time there is a request for the web page.

The amount of data sent back can be large and when it’s been sent back several times it compounds the problem.

The browser has to completely render the page each time it receives the content from the server.

The application does not feel responsive. You’re waiting for the server to give an update.

The site is not very interactive. If you don’t do anything with the page you’re not getting any feedback from the server.

When the first browser was created for rendering HTML, it was just that, a browser. New innovations were introduced for modern browsers (Fire Fox, Internet explorer 6+, Safari, and Opera) such as client side scripting languages (JavaScript, VBScript) and the availability of the Document Object Model (DOM). The average computer today and its browser are extremely powerful and are capable of doing more of the work that was traditionally done on the server side.

Finally, the number of potential people browsing your web application has increased and will continue to grow causing more work for your server(s). Reducing the workload by sending less content for each request, your web application will feel more responsive and will be capable of handling more users requesting content.

Let JavaScript and the browser do the talking!

Now let’s talk about the AJAX way. Instead of using the Form Tag to do the send requests to the server, we are going to use JavaScript to make the request. When the server sends back the information we use JavaScript to dynamically update the page without having to render the entire page all over again.

Another advantage is that the request is being made asynchronously (Hence the Asynchronous in AJAX).The user is still able to interact with the web application while the request is being made to the server. When the response from the server is returned to the browser, a call is made to a JavaScript function that handles the response. This is called a callback function. The advantage is that you’re not waiting around for updates to occur; this is what makes AJAX enabled web applications so powerful!

This concludes part 1 of 3 on Ajax Demystified.

Check out Part 2 where we go into more detail on how to actually write a simple AJAX app.