Datasheet

1
Introducing Ajax
The path of history is littered with splits, branches, and what-if’s. The pace of development of
technology is relentless and often merciless. Past battles have seen VHS triumph over Betamax,
PCs over microcomputers, Internet Explorer (IE) over Netscape Navigator, and plenty more simi-
lar conflicts are just waiting to happen in DVD formats. It doesn’t mean that one technology was
necessarily better than the other; it’s just that one format or technology had the features and func-
tionality required at that time to make it more popular. You’ll still find enthusiasts now waxing
lyrical about the benefits of Betamax tape, claiming that it was smaller, had better quality and
such. It doesn’t mean they were wrong. Perhaps they were being a little sad and obsessive, but
beneath it all, they had a point.
The evolution of the Internet has had its own such forks. One that continues to rumble is the so-
called “fat-client” versus “thin-client” debate. Briefly put, this is the choice between getting your
browser to do most of the work, as opposed to getting a server at the other end to do the process-
ing. Initially, in the mid-1990s, it looked as if the “fat-client” ideology was going to win out. The
introduction of IE 4 and Netscape Navigator 4 brought with them the advent of Dynamic HTML,
which used scripting languages to alter pages so that you could drag and drop items or make
menus appear and disappear without requiring a page refresh. Within a year, though, there was a
rush toward the “thin-client,” with the introduction of server-side technologies such as Active
Server Pages and PHP. The client-side techniques still exist, but the model of current Internet and
web page usage is broadly based on the server-side method of “enter your data, send the page to
the server, and wait for a response.”
When one format predominates in the stampede to adoption, you can often forget what was good
about the other format. For example, some aspects of page validation can be performed equally as
well on the browser. If you were to type “fake e-mail” into an e-mail textbox, you wouldn’t need to
go to the server to check this. JavaScript can perform a check for you equally as efficiently, and
also much more quickly. While plenty of people sensibly do validation on both client and server,
many pages attempt to perform the processing only on the server. If there has been one continual
bugbear about the Web, it is that it is slow. Timeouts, page-not-found errors, unresponsive buttons
and links haven’t gone away, despite the fact that bandwidth has increased tenfold. So, other ways
of addressing this sluggishness are becoming more common.
Companies have begun to reevaluate the way they are doing things to see if they can improve the
user experience on several levels making pages faster and more responsive, but also offering a
04_106754 ch01.qxp 2/9/07 6:15 PM Page 1
COPYRIGHTED MATERIAL

Summary of content (30 pages)

The following is incorrect nesting:

This is an incorrectly nested H1 tag

Although it might seem to go against the grain of HTML’s easygoing and easy-to-code nature, if a page isn’t correctly constructed, then you won’t be able to perform the kind of Ajax techniques discussed in this book. To use the DOM, the page has to be correctly formed.

  • PAGE 11

    Chapter 1: Introducing Ajax document.form1.button.value = “Click Me”; Or, you can use methods that can access the specific elements or subsets of elements on the page, such as the document.getElementById method, which will return a specific instance of an element that matches the criteria: var myTextBox = document.getElementById(“myTextbox”); You can then assign values to the variable you have created to alter the values. To make the text box invisible, you could call the following: myTextBox.style.

  • PAGE 12

    Chapter 1: Introducing Ajax A fair amount of Ajax code will deal with handling cross-browser code and handling errors if and when they arise, unless you can guarantee that your target audience will only ever use one browser (such as on a local intranet). This is an unfortunate set of circumstances that even new versions of IE and Firefox are not able to rectify. Later chapters address both of these dilemmas.

  • PAGE 13

    Chapter 1: Introducing Ajax And you get a resulting XML document (in this case, also an XHTML document) looking like this:

    Hotel Name Number of Rooms Location
    Hotel Shakespeare 50 Birmingham
    Hotel Washington

  • PAGE 14

    Chapter 1: Introducing Ajax You could then insert the XHTML document fragment into the HTML page dynamically to update the page. XSLT is another standard maintained by W3C. Both IE and Mozilla have XSLT processors; however, they don’t always treat their XSLT documents in the same way. XSLT uses another language, XPath, to query the XML document when applying its transformations.

  • PAGE 15

    Chapter 1: Introducing Ajax In Mozilla Firefox, IE 7, and other browsers, it is created as follows: var xHRObject = new XMLHttpRequest(); In turn, this means that you have to do a little bit of browser feature detection before you can determine in which way the object needs to be created. Because ActiveX controls and objects are unique to IE, you can test for them by attempting to call the ActiveXObject method of the window object.

  • PAGE 16

    Chapter 1: Introducing Ajax As with JavaScript, this book does not teach you how to use PHP and ASP.NET. It’s expected that you will know either one or the other. Server-side technologies are examined more closely in Chapter 3, but the current discussion attempts to avoid going into them in too much detail because they provide the glue for Ajax, rather than the backbone.

  • PAGE 17

    Chapter 1: Introducing Ajax As mentioned, this model works for browsing web pages, but the development of more and more complex web applications means that this model is now breaking down. The first area in which it breaks down is that of performance. The “enter, send, and wait” approach means there is wasted time. Second, whenever you refresh a page, you are sending a new request back to the server.

  • PAGE 18

    Chapter 1: Introducing Ajax Invisible Data Retrieval The longer you look at a web page, the greater its chance to go out of date. With an Ajax application, even though on the surface the web page might not be told to do anything, it could be updating itself behind the scenes. Constant Updating Because you’re not waiting for a page refresh every time, and because Ajax can retrieve data under the covers, the web application can be constantly updated.

  • PAGE 19

    Chapter 1: Introducing Ajax A considerable number of articles explain why you shouldn’t use Ajax techniques in certain situations, such as those found at the following URLS: ❑ Ajax sucks — http://www.usabilityviews.com/ajaxsucks.html (a spoof article on Jakob Nielsen’s why frames suck) ❑ Ajax promise or hype — http://www.quirksmode.org/blog/archives/2005/03/ ajax_promise_or.html ❑ Ajax is not cool — http://www.lastcraft.com/blog/index.

  • PAGE 20

    Chapter 1: Introducing Ajax You should be getting a feel by now that each of these reasons is qualified — the use of Ajax can hinder usability, not aid it; however, if development is considered, if you take steps to address the problems with Back buttons and bookmarks, then there’s no reason why Ajax techniques shouldn’t be used. It does raise a question, though.

  • PAGE 21

    Chapter 1: Introducing Ajax Creating an Ajax application is about the design and thinking about how the user interface and experience will be improved by your application. We’re going to create a quick example that shows how you can use the XMLHttpRequest object and XML files to create a dynamic menu system for a business scenario. The business scenario is this. You have a travel company whose web site displays information about hotels and suites.

  • PAGE 22

    Chapter 1: Introducing Ajax 1003 Family 6 90.00 10 3. Next, you must create a JavaScript script to handle the client-side processing. Save this as ajax.js, and, once again, in the Chapter1 folder. // Create the XMLHttpRequest var xHRObject = false; if (window.XMLHttpRequest) { xHRObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { xHRObject = new ActiveXObject(“Microsoft.

  • PAGE 23

    Chapter 1: Introducing Ajax var fragment = xsltProcessor.transformToFragment(xmlDoc, document); document.getElementById(“menuhere”).innerHTML = “”; document.getElementById(“menuhere”).appendChild(fragment); } if (spanb != null) { spanb.innerHTML = transform; } //Clear the object and call the getDocument function in 10 seconds xHRObject.abort(); setTimeout(“getDocument()”, 10000); } } function getDocument() { //Reset the function xHRObject.

  • PAGE 24

    Chapter 1: Introducing Ajax

  • Hotel London
    Hotel Rome
  • PAGE 25

    Chapter 1: Introducing Ajax 5. Next is the CSS, which controls the switching on and off of the dynamic submenu and the presentation of the menu blocks, such as the colors and font size. Save this as SuiteListStyles .css in the Chapter1 folder. td.menublock { background-color:#eeeeff; width:120px;height:25px;border-style:ridge; borderwidth:thin; border-color:gray; font-weight: bold; text-align:center; font-family: Arial; color:gray; } div.

  • PAGE 26

    Chapter 1: Introducing Ajax Just as with server-side technologies, the XMLHttpRequest object requires the server to work correctly. If it works correctly, you will see a page with five menu options on the left-hand side. Four of these options are inactive. The active option is Hotel Rome, and if you hover the mouse over it, you will see a blue menu appear (Figure 1-8). Figure 1-8: Hovering over the active option of Hotel Rome. 8. Now, this is the neat bit.

  • PAGE 27

    Chapter 1: Introducing Ajax 10. The top entry has disappeared. How It Works As mentioned previously, this discussion does not go into detail about this example because the techniques will be covered in later chapters. Instead, let’s look at what the application is doing and how the different parts fit together. We’ve created a simple menu system in an XSL template. This consists of a table with five rows. The XSL template takes its data from the XML document SuiteList.xml.

  • PAGE 28

    Chapter 1: Introducing Ajax // Create the XMLHttpRequest var xHRObject = false; if (window.XMLHttpRequest) { xHRObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { xHRObject = new ActiveXObject(“Microsoft.XMLHTTP”); } The other three steps are contained in the getDocument() function, which is loaded on startup, via the body element’s onload event handler: //Reset the function xHRObject.

  • PAGE 29

    Chapter 1: Introducing Ajax var fragment = xsltProcessor.transformToFragment(xmlDoc, document); document.getElementById(“menuhere”).innerHTML = “”; document.getElementById(“menuhere”).appendChild(fragment); } XSLT is browser-specific, so you have one branch for IE and one branch for Firefox, but they both do the same thing. They store the XML response, they load an XSL style sheet, and they perform a transform on it. The fragment is then inserted into the page at the element with the ID “menuhere”.

  • PAGE 30

    Chapter 1: Introducing Ajax an Ajax application. The discussion looked at why indiscriminate use of Ajax could have the reverse effect to the desired one. Examples showed some good Ajax applications in action, and the chapter discussed their techniques. Last, you created your own Ajax application that used a lot of the technologies to be discussed and used in this book. Exercises Suggested solutions to these questions can be found in Appendix A. 1. 2.