Pages

Saturday, January 24, 2009

Ajax it's a powerful approach to building Web sites and it's not nearly as hard to learn as an entire new language.
It is mainly based on Javascript and XML
Before seeing what Ajax is, though, let's spend just a few moments understanding what Ajax does.

When an application is written today, we have two basic choices:

  • Desktop applications
    Desktop applications usually installed completely on your computer. They might use the Internet to download updates, but the code that runs these applications resides on your desktop.

  • Web applications
    There's no surprise here -- run on a Web server somewhere and you access the application with your Web browser.



More important than where the code for these applications runs, is how they do interact. Desktop applications are usually pretty fast (they're running on your computer; you're not waiting on an Internet connection), & have great user interfaces (usually interacting with your operating system), and are incredibly dynamic.

On the other hand, Web applications are usually up-to-the-second current and they provide services you could never get on your desktop (yahoo and google). However, with the power of the Web comes waiting -- waiting for a server to respond, waiting for a screen to refresh, waiting for a request to come back and to generate a new page.
As you might already be suspecting, Ajax attempts to reduce the gap between the functionality and interactivity of a desktop application and the always-updated Web application.
Here dynamic user interfaces and fancy controls can be used.
So what are you waiting for? Start looking at Ajax and how to turn your clunky Web interfaces into responsive Ajax applications.

Here are the basic technologies involved in Ajax applications:

  • HTML is used to build Web forms and identify fields for use in the rest of your application.

  • JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.

  • DHTML, or Dynamic HTML, helps you update your forms dynamically. You'll use div, span, and other dynamic HTML elements to mark up your HTML.

  • DOM, the Document Object Model, will be used (through JavaScript code) to work with both the structure of your HTML and (in some cases) XML returned from the server.


The XMLHttpRequest object

The first object you want to understand is probably the one that's newest to you; it's called XMLHttpRequest. This is a JavaScript object and is created as simply as shown below..
Listing.. Create a new XMLHttpRequest object

<script language="javascript" type="text/javascript">

var xmlHttp = new XMLHttpRequest();

</script>

This object will be discussed in next part, but for now realize this object that handles all your server communication. Before going forward, stop and think about that -- it's the JavaScript technology through the XMLHttpRequest object that talks to the server. That's not the normal application flow and it's where Ajax gets much of its magic.Getting a Request object
With a basic overview under your belt, you're ready to look at a few specifics. Since XMLHttpRequest is central to Ajax applications -- and probably new to many of you -- I'll start there. As you saw in Listing 1, it should be pretty easy to create this object and use it, right? Wait a minute.
Remember those pesky browser wars from a few years back and how nothing worked the same across browsers? Well, believe it or not, those wars are still going on albeit on a much smaller scale. And, surprise: XMLHttpRequest is one of the victims of this war. So you'll need to do a few different things to get an XMLHttpRequest object going. I'll take your through it step by step.
Working with Microsoft browsersMicrosoft's browser, Internet Explorer, uses the MSXML parser for handling XML (you can find out more about MSXML in Resources). So when you write Ajax applications that need to work on Internet Explorer, you need to create the object in a particular way.
However, it's not that easy. MSXML actually has two different versions floating around depending on the version of JavaScript technology installed in Internet Explorer, so you've got to write code that handles both cases. Look at Listing below for the code that you need to create an XMLHttpRequest on Microsoft browsers.
Listing.. Create an XMLHttpRequest object on Microsoft browsers

var xmlHttp = false;
try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}

All of this won't make sense , but its OK. You'll dig into JavaScript programming, error handling, conditional compilation, and more before this series is finished. For now, you want to get two core lines into your head:
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
and
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");.

In whole, this code tries to create the object using one version of MSXML; if that fails, it then creates the object using the other version. Nice, huh? If neither of these work, the xmlHttp variable is set to false, to tell your code know that something hasn't worked. If that's the case, you've probably got a non-Microsoft browser and need to use different code to do the job.
Dealing with non-Microsoft browsers
If Internet Explorer isn't your browser of choice or you write code for non-Microsoft browsers, then you need different code. In fact, this is the really simple line of code you saw back in first Listing..
var xmlHttp = new XMLHttpRequest object;
This simpler line creates an XMLHttpRequest object in Mozilla, Chrome, Safari and several browsers any form or fashion.
The key is to support all browsers. Who wants to write an application that works just on Internet Explorer or an application that works just on non-Microsoft browsers? Worse yet, do you want to write your application twice? Of course not! So your code combines support for both Internet Explorerand non-Microsoft browsers. Listing below shows the code to do that.
Listing... Create an XMLHttpRequest object the multi-browser way

/* Create a new XMLHttpRequest object to talk to the Web server */

var xmlHttp = false;

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {

xmlHttp = new XMLHttpRequest();

}

Focus exclusively on XMLHttpRequest. The core of this code breaks down into three steps:

1. Create a variable, xmlHttp, to reference the XMLHttpRequest object that you will create.

2. Try and create the object in Microsoft browsers:

* Try and create the object using the Msxml2.XMLHTTP object.

* If that fails, try and create the object using the Microsoft.XMLHTTP object.

3. If xmlHttp still isn't set up, create the object in a non-Microsoft way.

At the end of this process, xmlHttp should reference a valid XMLHttpRequest object, no matter what browser your users run.
So you now understand Ajax and have a basic idea about the XMLHttpRequest object and how to create it.
If read read closely, one can realize that it's the JavaScript technology that talks to any Web application on the server rather than your submitting HTML form to application.
What's the missing piece? How to actually use XMLHttpRequest. Since this is critical code that you'll use in some form in every Ajax application you write, take a quick tour through what a basic request/response model with Ajax looks like.
Making a request

You have your shiny new XMLHttpRequest object; now take it for a spin. First, you need a JavaScript method that your Web page can call (like when a user types in text or selects an option from a menu). Then, you'll follow the same basic outline in almost all of your Ajax applications:

  1. Get whatever data you need from the Web form.

  2. Build the URL to connect to.

  3. Open a connection to the server.

  4. Set up a function for the server to run when it's done.

  5. Send the request.


Listing is a sample of an Ajax method that does these very things, in this order:
Listing.. Make a request with Ajax

function callServer() {

// Get the city and state from the web form

var city = document.getElementById("city").value;

var state = document.getElementById("state").value;

// Only go on if there are values for both fields

if ((city == null) || (city == "")) return;

if ((state == null) || (state == "")) return;

// Build the URL to connect to

var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);

// Open a connection to the server

xmlHttp.open("GET", url, true);

// Setup a function for the server to run when it's done

xmlHttp.onreadystatechange = updatePage;

// Send the request

xmlHttp.send(null);

}


A lot of this is self-explanatory. The first bit of the code uses basic JavaScript code to grab the values of a few form fields. Then the code sets up a PHP script as the destination to connect to. Notice how the URL of the script is specified and then the city and state (from the form) are appended to this using simple GET parameters.

Next, a connection is opened; here's the first place you see XMLHttpRequest in action again. The method of connection is indicated (GET), as well as the URL to connect to. The final parameter, when set to true, requests an asynchronous connection (thus making this Ajax). If you used false, the code would wait around on the server when the request was made and not continue until a response was received. By setting this to true, your users can still use the form (and even call other JavaScript methods) while the server is processing this request in the background.

The onreadystatechange property of xmlHttp (remember, that's your instance of the XMLHttpRequest object) allows you to tell the server what to do when it does finish running (which could be in five minutes or five hours). Since the code isn't going to wait around for the server, you'll need to let the server know what to do so you can respond to it. In this case, a specific method -- called updatePage() -- will be triggered when the server is finished processing your request.

Finally, send() is called with a value of null. Since you've added the data to send to the server (the city and state) in the request URL, you don't need to send anything in the request. So this fires off your request and the server can do what you asked it to do.

If you don't get anything else out of this, notice how straightforward and simple this is! Other than getting the asynchronous nature of Ajax into your head, this is relatively simple stuff. You'll appreciate how it frees you up to concentrate on cool applications and interfaces rather than complicated HTTP request/response code.

The code at last Listing is about as easy as it gets. The data is simple text and can be included as part of the request URL. GET sends the request rather than the more complicated POST. There's no XML or content headers to add, no data to send in the body of the request -- this is Ajax simplicity, in other words.

Don't get panic; things will become more complicated as series progresses. You'll learn sending POST requests, setting headers and content types, encoding XML in request, how to add security to your request so on!

Don't worry about this stuff for now; get your concentration around basics, and sooner you could build up a whole set of Ajax tools.

Handling the response


Now time to handle the servers' response. You really only need to know two things at this point:

  • Don't do anything until the xmlHttp.readyState property is equal to 4.

  • The server will stuff it's response into the xmlHttp.responseText property.


The first of these ready states is going to take up the bulk of the next article. For now, simply check for a certain value (4), things will work.
The second one using xmlHttp.responseText property for getting server's response -- is easy. Next Listing provides an example of a method that the server can call based on the values sent in previous listing.
Listing.. Handle the server's response

function updatePage() {

if (xmlHttp.readyState == 4) {

var response = xmlHttp.responseText;

document.getElementById("zipCode").value = response;

}

}

This code is not difficult or complicated. Waits until server sends with proper readyState and then uses the value that the server returns to set the value of another form field; with this suddenly a pincode will appear in the control provided for it -- but the user never had to click a button!. That's the feel of desktop that is described earlier. Responsiveness, a dynamic feel, and more, or less like a Javacsript code.
Readers might notice that the pincode field is normal text field. Once the server returns the ZIP code and the updatePage() method sets the value of that field with the city/state ZIP code, users can override the value.

0 comments: