Ajax Ajax by HTML, JavaScript? Technology, DHTML, and DOM, an excellent way to translate awkward Web interfaces into interactive Ajax applications.
The author of this article is an Ajax expert who demonstrates how these technologies work together-from a general overview to a detailed discussion-to make efficient WEB development a reality. He also uncovered the mysteries of Ajax's core concepts, including XMLHttpRequest objects.
Five years ago, if you didn't know XML, you were an ugly duckling that nobody paid attention to. 18 months ago, Ruby became the center of attention, not knowing that Ruby programmers had to be on the bench. Today, if you want to keep up with the latest technology trends, your goal is Ajax.
But Ajax is not just a fashion, it's a powerful way to build a Web site, and it's not as difficult as learning a whole new language.
But before we go into the details of what Ajax is, let's take a few minutes to learn what Ajax does. Currently, there are two basic options for writing applications:
Desktop applications
WEB Application
The two are similar, and desktop applications are typically CD-media (sometimes downloaded from a Web site) and fully installed on your computer. Desktop applications may download updates using the Internet, but the code to run these applications is on the desktop computer. Web applications run on a Web server somewhere--not surprisingly, to access this application through a Web browser.
However, more important than where the running code of these applications is, is how the application works and how it interacts with it. Desktop applications are generally fast (running on your computer without waiting for an internet connection), with a beautiful user interface (usually related to the operating system) and extraordinary dynamics. You can click, select, enter, open menus and submenus, cruise around, and basically don't have to wait.
Web applications, on the other hand, are the latest trends that provide services that cannot be implemented on the desktop (such as Amazon.com and EBay). However, as the Web is strong, waiting waits, waits for the server to respond, waits for the screen to refresh, waits for the request to return and produces the new page.
It is obvious that this is said briefly, but the basic concept is this. As you may have guessed, Ajax is trying to build the functionality and interactivity of desktop applications, and the bridge between constantly updated Web applications. You can use the dynamic user interface and beautiful controls that are common in desktop applications, but in WEB applications.
What are you waiting for? Let's look at how Ajax translates a clumsy Web interface into an AJAX application that responds quickly.
Old technology, new skills
When it comes to Ajax, it actually involves a variety of technologies, and the flexibility to use it requires a deeper understanding of these different technologies (the first few articles in this series will discuss them separately). The good news is that you may already be familiar with most of these technologies, and better yet, that they are easy to learn and not as difficult as a complete programming language, such as Java or Ruby.
Definition of Ajax
By the way, Ajax is the abbreviation for asynchronous JavaScript and XML (and DHTML, etc.). This phrase was invented by Jesse James Garrett of Adaptive Path (see Resources), which, according to Jesse, is not an acronym.
The following are the basic techniques used by AJAX applications:
HTML is used to build Web forms and determine which fields are used by other parts of the application.
JavaScript code is the core code for running Ajax applications, helping to improve communication with server applications.
DHTML or dynamic HTML, which is used to dynamically update forms. We will use Div, span, and other dynamic HTML elements to mark HTML.
The Document Object Model DOM is used (through JavaScript code) to handle the HTML structure and, in some cases, the XML returned by the server.
We are here to further analyze the responsibilities of these technologies. I'll delve into these technologies in a future article, as long as you are familiar with these components and technologies. The more familiar these codes are, the easier it is to move from a fragmented understanding of these technologies to a real grasp of those technologies (and also really open the door to WEB application development).
XMLHttpRequest objects
One of the objects you want to know is probably the most unfamiliar to you, XMLHttpRequest. This is a JavaScript object, and creating the object is simple, as shown in Listing 1.
Listing 1. Create a new XMLHttpRequest object
This object is discussed further in the next installment, and now you know that this is the object that handles all server traffic. Before you go on, stop and think: The JavaScript technology is a conversation with the server through the XMLHttpRequest object. This is not a generic application flow, which is precisely the source of the powerful functionality of Ajax.
In a typical WEB application, users fill Out form fields and click the Submit button. The entire form is then sent to the server, and the server forwards it to the script that handles the form (usually PHP or Java, or maybe a CGI process or something like that), and then sends it back to the new page after the execution of the script completes. The page may be HTML with a new form that has already populated some data, a confirmation page, or a page that has some options selected based on the input data from the original form. Of course, users must wait when a script or program on the server processes and returns a new form. The screen becomes blank until the server returns data and then redraw it. This is why interactivity is poor, and users don't get immediate feedback, so they feel different from desktop applications.
Ajax basically puts JavaScript technology and XMLHttpRequest objects between Web forms and servers. When a user fills out a form, the data is sent to some JavaScript code instead of being sent directly to the server. Instead, the JavaScript code captures the form data and sends the request to the server. Also, the form on the user's screen does not blink, disappear, or delay. In other words, JavaScript code sends a request behind the scenes, and the user doesn't even know the request is sent. Better yet, requests are sent asynchronously, meaning that JavaScript code (and users) does not have to wait for a response from the server. So users can continue to enter data, scroll the screen, and use the application.
The server then returns the data to the JavaScript code (still in the Web form), which determines how to process the data. It can quickly update form data, making people feel that the application is done immediately, the form is not submitted or refreshed, and the user gets the new data. JavaScript code can even perform some sort of calculation on the received data, and then send another request without user intervention at all! This is the strength of XMLHttpRequest. It can interact with the server on its own, and users may even have no idea what's going on behind the scenes. The result is a dynamic, fast-response, highly interactive experience similar to desktop applications, but with all the power of the internet behind it.
Add some JavaScript
After you get the XMLHttpRequest handle, the other JavaScript code is very simple. In fact, we'll use JavaScript code to do very basic tasks:
Get form data: JavaScript code can easily extract data from an HTML form and send it to the server.
Modify the data on the form: It is also easy to update the form, from setting the field value to replacing the image quickly.
Parsing HTML and XML: Manipulating the DOM using JavaScript code (see the next section) to handle the structure of the XML data returned by the HTML form server.
For the first two points, you need to be very familiar with the getElementById () method, as shown in Listing 2.
Listing 2. Capturing and setting field values in JavaScript code
Get the value of the ' phone ' field and stuff it in a variable called phone
var phone = document.getElementById ("Phone"). Value;
Set Some values on a form using an array called response
document.getElementById ("Order"). Value = Response[0];
document.getElementById ("Address"). Value = Response[1];
There is no particular place to watch, it's great! You should realize that there is nothing very complicated here. Just master the rest of the Xmlhttprequest,ajax application is the simple JavaScript code shown in Listing 2, mixed with a small amount of HTML. At the same time, use a little DOM, let's take a look.
End With DOM
Finally, there is the DOM, the Document Object model. DOM may be a bit intimidating for some readers, and it's rarely used by HTML designers, even by JavaScript programmers, unless a high-end programming task is done. A large number of DOM-intensive uses are complex Java and C + + programs, which may be the reason Dom is considered difficult to learn.
Fortunately, it's easy and intuitive to use DOM in JavaScript technology. Now it might be a rule to explain how to use the DOM, or at least give some sample code, but that might also mislead you. Even ignoring the DOM, I can still delve into Ajax, which is the approach I'm going to take. The DOM will be discussed again in future articles, as long as you know it might be needed. When it comes to passing XML and changing HTML forms between JavaScript code and the server, we delve into the DOM. You can do some interesting work without it, so put the DOM aside for now.
Back to the top of the page
Get the Request object
With the basics above, let's take a look at some concrete examples. XMLHttpRequest is the core of AJAX applications and may be unfamiliar to many readers, so let's start here. As you can see from listing 1, creating and using this object is very simple, isn't it? Wait a minute.
Remember those pesky browser wars a couple of years ago? There is no such thing as a different browser to get the same result. Whether you believe it or not, these wars are still going on, albeit on a smaller scale. But strangely enough, XMLHttpRequest became one of the victims of this war. So getting XMLHttpRequest objects may require a different approach. I'll explain it in detail below.
Using Microsoft Browser
Microsoft Browser Internet Explorer uses the MSXML parser to work with XML (you can learn more about MSXML through resources). So if you are writing an AJAX application that is dealing with Internet Explorer, you must create the object in a special way.
But it's not that simple. Depending on the version of JavaScript technology installed in Internet Explorer, MSXML actually has two different versions, so you must write code for each of these two situations. See listing 3, where the code creates a xmlhttprequest on a Microsoft browser.
Listing 3. Create a XMLHttpRequest object on a Microsoft browser
var xmlHttp = false;
try {
XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (E2) {
XmlHttp = false;
}
}
You may not fully understand the code, but it doesn't matter. When this series ends, you will have a deeper understanding of JavaScript programming, error handling, conditional compilation, and more. Now just keep in mind the two lines of code:
XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
And
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");.
These two lines of code are basically trying to create an object using one version of MSXML, and if it fails, create the object with a different version. Nice, huh? If none succeeds, set the XMLHTTP variable to False to tell you that there is a problem with your code. If this happens, it may be that a non-Microsoft browser is installed and you need to use different code.
Working with Mozilla and non-Microsoft browsers
If you choose a browser other than Internet Explorer, or you write code for a non-Microsoft browser, you need to use different code. In fact, this is the simple line of code shown in Listing 1:
var xmlHttp = new XMLHttpRequest object;.
This much simpler code creates the XMLHttpRequest object in Mozilla, Firefox, Safari, Opera, and virtually all non-Microsoft browsers that support Ajax in any form or mode.
Combined
The key is to support all browsers. Who wants to write an application that can only be used for Internet Explorer or non-Microsoft browsers? Or worse, write an application two times? Of course not! Therefore, the code should support both Internet Explorer and non-Microsoft browsers. Listing 4 shows such a code.
Listing 4. Create a XMLHttpRequest object in a variety of browser-enabled ways
/* Create A new XMLHttpRequest object to talk to the WEB server * *
var xmlHttp = false;
/ * @cc_on @*/
/ * @if (@_jscript_version >= 5)
try {
XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (E2) {
XmlHttp = false;
}
}
@end @*/
if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {
XmlHttp = new XMLHttpRequest ();
}
Now, regardless of the strange notations that are commented out, such as @cc_on, this is a special JavaScript compiler command that will be discussed in detail in the next issue of the XMLHttpRequest article. The core of this piece of code is divided into three steps:
1. Establish a variable XMLHTTP to refer to the XMLHttpRequest object that is about to be created.
2. Try to create the object in a Microsoft browser:
o Try to create it using the Msxml2.xmlhttp object.
o if it fails, try microsoft.xmlhttp the object again.
3. If XMLHTTP is still not established, the object is created in a non-Microsoft way.
Finally, XMLHTTP should refer to a valid XMLHttpRequest object, no matter what browser is running.
A little explanation of security
What about security? Browsers now allow users to improve their security levels, turn off JavaScript technology, and disable any options in the browser. In this case, the code will not work anyway. The problem must be dealt with properly at this time, which requires a separate article to discuss, to be put in the future (this series is long enough?). Don't worry, you may have mastered it before you finish reading it. Writing a robust but less-than-perfect code now is good for mastering Ajax. We will discuss more details in the future.
Back to the top of the page
Requests/responses in the Ajax world
Now that we've covered Ajax, we have a basic understanding of the XMLHttpRequest object and how to create it. If you read carefully, you may already know that JavaScript technology is dealing with WEB applications on the server, rather than HTML forms that are submitted directly to that application.
What else is missing? How to use XMLHttpRequest in the end. Because this code is very important, every AJAX application you write will have to use it in some way, first look at the basic AJAX request/response model.
Making a request
You've got a brand-new XMLHttpRequest object, now let it do something. First you need a JavaScript method that a Web page can invoke (for example, when the user enters text or selects an item from the menu). The next step is a process that is basically identical in all Ajax applications:
1. Get the data you need from your Web form.
2. Establish the URL to connect to.
3. Open the connection to the server.
4. Set the function that the server will run after it completes.
5. Send the request.
The example Ajax method in Listing 5 is organized in this order:
Listing 5. Making an Ajax request
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 in 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);
}
Most of the code has a clear meaning. The starting code obtains the values of several form fields using basic JavaScript code. Then set a PHP script as the target of the link. Notice how the script URL is specified, and city and state (from the form) are appended to the URL with a simple get parameter.
Then open a connection, which is the first time you see Using XMLHttpRequest. The connection method (get) and the URL to connect are specified. If the last argument is set to True, an asynchronous connection will be requested (this is the origin of Ajax). If you use False, the code will wait for the response returned by the server after it makes a request. If set to True, the user can still use the form (or even invoke other JavaScript methods) when the server is processing the request in the background.
XmlHttp (Remember, this is the XMLHttpRequest object instance) onReadyStateChange property tells the server what to do after the run is completed (it may take five minutes or five hours). Because the code does not wait for the server, you must let the server know what to do so that you can respond. In this example, if the server has finished processing the request, a special method named Updatepage () will be triggered.
Finally, use the value NULL to call Send (). Because the data to be sent to the server (city and state) has been added to the request URL, no data needs to be sent in the request. This makes the request, and the server works according to your requirements.
If you don't find anything new, you should realize how simple and clear it is! In addition to remembering the asynchronous nature of Ajax, these things are fairly straightforward. It should be appreciated that Ajax allows you to concentrate on writing beautiful applications and interfaces without worrying about complex HTTP request/response code.
The code in Listing 5 illustrates the ease of use of Ajax. The data is a simple text that can be used as part of the request URL. Send a request with a get instead of a more complex POST. There is no XML and the header to add, there is no data to send in the request body, in other words, this is the utopia of Ajax.
Don't worry, things will get more and more complicated as this series of articles unfolds. You'll see how to send POST requests, how to set request headers and content types, how to encode XML in messages, how to increase the security of your request, and there's a lot more you can do! For the time being, you don't have to take care of the difficult points, just master the basics and soon we'll build a whole suite of Ajax tools.
Handling Responses
Now you have to face the server response. Now just know two points:
Do nothing until the value of the Xmlhttp.readystate property equals 4.
The server populates the Xmlhttp.responsetext property with the response.
The 1th, ready state, will be discussed in more detail in the next article, and you will learn more about the HTTP request phase than you might have imagined. Now it's OK to just check a specific value (4) (There are more values to introduce in the next installment). 2nd, using the Xmlhttp.responsetext property to get the server's response is simple. The example method in Listing 6 is available for the server to call based on the data that is sent in Listing 5.
Listing 6. Handling Server Responses
function Updatepage () {
if (xmlhttp.readystate = = 4) {
var response = Xmlhttp.responsetext;
document.getElementById ("ZipCode"). Value = response;
}
}
The code is also neither difficult nor complex. It waits for the server to invoke and, if it is ready, sets the value of another form field using the value returned by the server (here is the ZIP encoding of the city and state that the user entered). The ZipCode field that contains the ZIP code suddenly appears, and the user does not press any buttons! This is what the desktop application feels like before. Quick response, dynamic feeling, and so on, all because of a little bit of Ajax code.
Attentive readers may notice that ZipCode is an ordinary text field. Once the server returns a ZIP code, the Updatepage () method sets the value of that field with the city/State zip code, and the user can overwrite the value. There are two reasons for doing this: keeping the example simple means that you may sometimes want users to be able to modify the data returned by the server. To keep these two points in mind, they are important for good user interface design.
Back to the top of the page
Connecting Web Forms
What else is there? Actually, not much. A JavaScript method captures the user's input form information and sends it to the server, and another JavaScript method listens and processes the response and sets the value of the field when the response is returned. All of this actually relies on invoking the first JavaScript method, which starts the entire process. The most obvious way is to add a button to the HTML form, but this is the 2001 approach, don't you think? Or use JavaScript technology like Listing 7.
Listing 7. Start an Ajax process
city: />
state: />
zip Code:
If it feels like a fairly common code, that's right, that's it! When a user enters a new value in the City or state field, the CallServer () method is triggered, and Ajax begins to run. Do you understand what's going on? Well, that's it!
Back to the top of the page
Conclusion
Now you may be ready to start writing your first Ajax application, or at least want to read the articles in the Resources section? But you can start with the basic concepts of how these applications work, and have a basic understanding of XMLHttpRequest objects. In the next installment, you'll learn how to handle JavaScript and server communication, how to use HTML forms, and how to get DOM handles.
Now take a moment to think about how powerful Ajax applications are. Imagine what it would be like for a Web form to respond immediately when you click a button, enter a field, select an option from the combo box, or drag the mouse over the screen. Think about what it means to be asynchronous, think about it. JavaScript code runs and does not wait for the server to respond to its request. What kind of problems will you encounter? What kind of field will it enter? Given this new approach, how do you change the design of your form when you are programming?
If you spend a little time on these issues, the benefits will be much more than simply cutting/pasting some code into an application that you simply don't understand. In the next installment, we'll put these concepts into practice, detailing the code needed to make the application work in this way. So now enjoy the possibilities that Ajax brings.
Back to the top of the page
Resources
Learn
You can refer to the English version of this article at the DeveloperWorks Global site.
Adaptive Path is a leading user interface design company that can read more about Ajax with a closer look at their website.
If you care about the origins of the word Ajax, take a look at Jesse James Garrett and his Ajax article (such as this one).
To learn more about the subject XMLHttpRequest object for the next installment, read this article about the XMLHttpRequest object.
If you use Internet Explorer, you can access the XML Developer Center of Microsoft Developer network.
Ajax for Java developers: Building dynamic Java Applications (developerworks,2005 September) introduces this innovative approach that addresses the problem of page reloading and creates a dynamic WEB application experience.
Ajax:ajax Java object Serialization for Java Developers (developerworks,2005 year October) describes five ways to serialize data in an Ajax application.
Using AJAX with PHP and Sajax (developerworks,2005 year October), this tutorial describes dynamic updates using AJAX and PHP for people interested in developing rich Web applications.
Call SOAP Web Services and Ajax, part 1:build the Web Services Client (developerworks,2005 year October), describes how to implement a W based design pattern using Ajax EB Browser's SOAP Web service client.
XML problem: Beyond DOM (developerworks,2005 year May) details how to use the Document Object model to build dynamic WEB applications.
Build apps with asynchronous JavaScript with XML, or Ajax (developerworks,2005 year November) demonstrates how to use AJAX constructs to support real-time validation of WEB applications.
Ajax for Java developers: Using Ajax (developerworks,2005 year November) with Direct Web Remoting demonstrates how to automate the tedious details of Ajax.
OSA Foundation has a wiki that investigates the Ajax/javascript library.
The object reference section of the XUL Planet details the XMLHttpRequest objects (not to mention the various other XML objects, such as DOM, CSS, HTML, Web Service, and Windows and navigation objects).
For the basics of AJax, read the policy white paper.
Take a look at some of the great Ajax apps shown on flickr.com.
Google's GMail is another example of a revolutionary WEB application that exploits Ajax.
Head Rush Ajax (O ' Reilly Media, inc.,2006 year February) contains this article as well as the content described in this series (and more) and employs the innovative award-winning format head.
Javascript:the Definitive Guide, 4th edition (O ' Reilly Media, inc.,2001 year November) is a good source of information about JavaScript language and the use of dynamic Web pages.
The DeveloperWorks Web Architecture area specializes in publishing articles on a variety of web-based solutions.