As with all form data, you can use either the POST or the GET method when requesting XML data—your choice will make little difference to the result. Why use XML? You may ask why you would use XML other than for fetching XML documents such as RSS feeds. Well, the simple answer is that you don’t have to, but if you wish to pass structured data back to your Ajax applications, it could be a real pain to send a simple, unorganized jumble of text that would need complicated processing in JavaScript. Instead, you can create an XML document and pass that back to the Ajax function, which will automatically place it into a DOM tree as easily accessible as the HTML DOM object with which you are now familiar. Now that you’ve learned how Ajax works in raw form, in the next chapter we’ll look at the popular YUI library, which is a framework that makes Ajax and other JavaScript even easier to use. Test Your Knowledge: Questions Question 18-1 Why is it necessary to write a function for creating new XMLHttpRequest objects? Question 18-2 What is the purpose of the try catch construct? Question 18-3 How many properties and how many methods does an XMLHttpRequest object have? Question 18-4 How can you tell when an Ajax call has completed? Question 18-5 How do you know whether an Ajax call completed successfully? Question 18-6 What XMLHttpRequest object’s property returns an Ajax text response? Question 18-7 What XMLHttpRequest object’s property returns an Ajax XML response? Question 18-8 How can you specify a callback function to handle Ajax responses? Question 18-9 What XMLHttpRequest method is used to initiate an Ajax request? Test Your Knowledge: Questions | 391 Question 18-10 What are the main differences between an Ajax GET and POST request? See the section “Chapter 18 Answers” on page 450 in Appendix A for the answers to these questions. 392 | Chapter 18: Using Ajax CHAPTER 19 Using YUI for Ajax and More Let’s face it: JavaScript isn’t the easiest programming language to master, particularly if you’ve never come across such an object-oriented approach before. And this is true also because Microsoft has, until relatively recently, steadfastly ignored web standards, resulting in the need to spend a lot of time writing cross-browser-compatible code. Thankfully, though, several organizations have set about trying to make JavaScript a much simpler and even more powerful language by creating frameworks for it. What they do is write wrappers around the JavaScript to break down complex tasks into small, more easily manageable ones. At the same time, they ensure that their framework methods are fully cross-browser compatible. Choosing a Framework The new difficulty now is choosing among the bewildering variety of frameworks. Some of the more popular of which are listed in Table 19-1. Table 19-1. Some popular JavaScript frameworks Framework Web address ASP.NET Ajax Framework http://asp.net/ajax Clean Ajax Framework http://sourceforge.net/projects/clean-ajax Dojo Toolkit http://dojotoolkit.org jQuery http://jquery.com MochiKit http://mochikit.com MooTools http://mootools.net OpenJS http://openjs.com Prototype http://prototypejs.org Rialto http://rialto.improve-technologies.com/wiki script.aculo.us http://script.aculo.us 393 Framework Web address Spry Framework http://labs.adobe.com/technologies/spry YUI http://developer.yahoo.com/yui Because each of these frameworks works differently, I have opted to settle on just one of them—the YUI framework—for this chapter. I made this decision because it was originally written by programmers at Yahoo!, which since then has allowed the Java- Script community as a whole to contribute code to the project. As a result, it’s a solid framework used across all the Yahoo! properties and also by tens of thousands of de- velopers around the world. What’s more, you can download the entire framework and an extensive collection of more than 300 example programs, along with a comprehensive amount of documen- tation, amounting to over 70 MB of data once uncompressed. But although I say “you can,” you don’t have to, because all of these scripts and the documentation appear on the YUI developer website, and you are permitted to simply link to each YUI script directly from Yahoo’s servers. Using YUI To get started with YUI, visit the following URL to download the complete distribution to your hard disk, where you can work on it locally: http://developer.yahoo.com/yui/download The download is about 11 MB in size and is supplied as a ZIP file that you will need to decompress. Once this is done, you will have a folder with a name such as yui_2.7.0b, depending on the version downloaded, inside of which will be another folder simply called yui. Navigate to this folder and load up the index.html file that you’ll find there into your browser to see a web page like that shown in Figure 19-1. In the same directory where index.html resides, you’ll also see a number of others. In particular I’d like to point you in the direction of the build folder, which contains about 60 subfolders that hold all the framework scripts (see Figure 19-2). You can copy the ones you need from here directly to your website, or access the ones on Yahoo’s website by referencing http://yui.yahooapis.com/2.7.0/build/ followed by the folder and script name. (Without the latter two names, this URL will call up an error page.) For example, you could copy the file yahoo.js from the build/yahoo folder to your web- site and link to it like this: <script src="yahoo.js"></script> Or you could link directly to Yahoo’s copy, like this: <script src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo.js"></script> 394 | Chapter 19: Using YUI for Ajax and More Figure 19-1. The YUI documentation main page Figure 19-2. The build folder, which contains the .js framework files Using YUI | 395 If you link directly, make sure to change the version folder name from 2.7.0 if you are using a newer version of YUI. Compressed Versions If you wish to speed up loading of these framework files, you can use the alternate “min” versions Yahoo! supplies. For example, yahoo.js is about 33 KB in size, but there is a file called yahoo-min.js that acts identically; by simply removing unnecessary whitespace and other text, the developers have compressed it down to under 6 KB in size. (There are tools on the Internet that let you minimize your own scripts, in case you think doing so will speed up loading significantly.) Using YUI for Ajax In the previous chapter, we used XMLHttpRequest objects to provide Ajax connectivity between the web browser, a server, and a third-party server. The process wasn’t too difficult, but it was a bit fiddly due to differences between implementations in different browsers. With YUI, handling Ajax becomes a whole lot easier, because it provides a range of cross-browser methods that will work on any major browser. What’s more, they re- move the need for you to output headers and perform other bits and pieces for POST requests, and so on. The upshot is that you can replace about 35 lines of code with a dozen or less. This makes your programs much easier to write and debug, and removes all the lower-level stuff, leaving it up to YUI to deal with. Including the framework files To perform Ajax calls with YUI, you need to include the following three framework files (I have chosen to use the compressed versions for speed): yahoo-min.js The main YUI file, generally required event-min.js The event handling framework file, used here for the callback connection-min.js The Ajax handling framework file If you copy those files from the relevant subfolders within the build folder to your web folder, your program can load the files using the following code: <script src="yahoo-min.js"></script> <script src="event-min.js"></script> <script src="connection-min.js"></script> 396 | Chapter 19: Using YUI for Ajax and More Or you can fetch them directly from Yahoo’s website using the following code: <script src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js"></script> <script src="http://yui.yahooapis.com/2.7.0/build/event/event-min.js"></script> <script src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"> </script> The YUI asyncRequest method Now all you need to do is call asyncRequest, Yahoo’s version of the ajaxRequest function we created in the last chapter. The syntax is: YAHOO.util.Connect.asyncRequest('method', 'url', callback [, 'parameters ']) The method to use is either POST or GET; the url should be a PHP script on your server. If you’re using the GET method, the name of the script should be followed by a ? and the parameter/value pairs you wish to send. The callback needs to point to a pair of functions to handle either successful completion or failure, and the parameters are passed only when you are using the POST method and the target server requires param- eters for the request. So an Ajax GET request might look like this: YAHOO.util.Connect.asyncRequest('GET', 'program.php', callback) The callback object should be created like this: callback = { success:successHandler, failure:failureHandler } The successHandler and failureHandler functions should contain instructions for your program to execute according to the intention of your project. An Ajax GET example using YUI Let’s take Example 18-4 from the previous chapter and see what it looks like when modified to use YUI (see Example 19-1, yuiurlget.html). Example 19-1. yuiurlget.html <html><head><title>YUI GET Example</title> </head><body><center /> <h2>Loading a web page into a DIV with YUI</h2> <div id='info'>This sentence will be replaced</div> <script src="yahoo-min.js"></script> <script src="event-min.js"></script> <script src="connection-min.js"></script> <script> url = "yahoo.com" callback = { success:successHandler, failure:failureHandler } request = YAHOO.util.Connect.asyncRequest('GET', 'urlget.php?url=' + url, callback) function successHandler(o) { document.getElementById('info').innerHTML = o.responseText } Using YUI | 397 function failureHandler(o) { document.getElementById('info').innerHTML = o.status + " " + o.statusText } </script></body></html> I’m sure you’ll agree that this is very simple indeed. After setting up the web page, displaying a heading, and creating the DIV in which to place the Ajax response, the program loads three YUI framework files. The rest of the document (less than 10 lines of code) is the Ajax, which does the following: 1. Place the URL to fetch, yahoo.com, in the variable url. 2. Create the callback object. This is an associative array that points to the handlers to be called in case of the success or failure of the call. 3. Place the Ajax call, which is a GET request to the URL urlget.php?url=yahoo.com. You may recall that we wrote urlget.php in the previous chapter (Example 18-5) and, as it doesn’t require modifying, I won’t repeat it here. Suffice it to say that the program fetches the HTML page at http://yahoo.com and returns it to the Ajax method. All that remains are the two functions for success or failure of the call. The success function, successHandler, simply places the Ajax response text into the DIV that we prepared for it, and failureHandler displays an appropriate message upon error. The result of calling up this new document in your browser can be seen in Figure 19-3. Figure 19-3. The result of calling up yuiurlget.html in a browser 398 | Chapter 19: Using YUI for Ajax and More An Ajax XML example using YUI Now let’s see how you can use the asyncRequest method with XML by calling up the Yahoo! RSS weather feed for Washington, D.C., using Example 19-2, yuixmlget.html. Example 19-2. yuixmlget.html <html><head><title>YUI XML Example</title> </head><body> <h2>Loading XML content into a DIV with YUI</h2> <div id='info'>This sentence will be replaced</div> <script src="yahoo-min.js"></script> <script src="event-min.js"></script> <script src="connection-min.js"></script> <script> url = encodeURI("xml.weather.yahoo.com/forecastrss?p=20500") callback = { success:successHandler, failure:failureHandler } request = YAHOO.util.Connect.asyncRequest('GET', 'xmlget.php?url=' + url, callback) function successHandler(o) { root = o.responseXML.documentElement; title = root.getElementsByTagName('description')[0]. firstChild.nodeValue date = root.getElementsByTagName('lastBuildDate')[0]. firstChild.nodeValue text = root.getElementsByTagName('description')[1]. firstChild.nodeValue document.getElementById('info').innerHTML = title + "<br />" + date + "<br />" + text } function failureHandler(o) { document.getElementById('info').innerHTML = o.status + " " + o.statusText } </script></body></html> This document is fairly similar to the previous one, in that the same YUI framework scripts are included, but right away, you’ll notice that the url is different. Because the weather feed itself takes GET parameters using a ? symbol, we have to URI-encode it as follows: url = encodeURI("xml.weather.yahoo.com/forecastrss?p=20500") This encoding has the effect of turning any special characters into a form that will not confuse the PHP program into thinking that additional parameters have been passed. Next, you’ll see that the callback object is the same as before, so we’ll gloss over that and move on to the request, which has only a name change from urlget.php to xmlget.php in order to call the correct PHP program for XML. The xmlget.php program is the same one we created in the previous chapter (see Example 18-6) and thus doesn’t need repeating here. Using YUI | 399 You’ll also notice that the function failureHandler is identical. So the main remaining change is in successHandler. This function refers to responseXML instead of responseText, from which it extracts the title, date, and text from the RSS feed and then inserts them into the DIV we prepared. The result of calling up yuixmlget.html into a browser can be seen in Figure 19-4. Other Uses for YUI The YUI framework offers support in a wide range of areas, including animation, but- tons, calendars, charts, colors, cookies, drag and drop, fonts, imaging, menus, styles, uploading, and a great deal more as well. To find features you need, check out the examples down the left of the main index.html page in the downloaded distribution or at http://developer.yahoo.com/yui and click on ones that interest you. Figure 19-4. The result of calling up yuixmlget.html in a browser 400 | Chapter 19: Using YUI for Ajax and More . urlget.php to xmlget.php in order to call the correct PHP program for XML. The xmlget.php program is the same one we created in the previous chapter (see Example 1 8-6 ) and thus doesn’t need repeating. http://sourceforge.net/projects/clean-ajax Dojo Toolkit http://dojotoolkit.org jQuery http://jquery.com MochiKit http://mochikit.com MooTools http://mootools.net OpenJS http://openjs.com Prototype http://prototypejs.org Rialto. the more popular of which are listed in Table 1 9-1 . Table 1 9-1 . Some popular JavaScript frameworks Framework Web address ASP.NET Ajax Framework http://asp.net/ajax Clean Ajax Framework http://sourceforge.net/projects/clean-ajax Dojo