APPENDIX A ■ ■ ■ The XMLHttpRequest Object
More often than not, chances are you will use some sort of library to do your Ajax work. Some of the libraries out there—only a handful of which we talked about in this book—really do make it far easier to work the “Ajax way.” That being said, there are times when you will want to go “bare metal,” so to speak, and use the XMLHttpRequest object yourself. In those instances, this appendix will be an invaluable aid to you.
What Is the XMLHttpRequest Object? XMLHttpRequest is an object (an ActiveX object in Microsoft Internet Explorer, a native component in most other browsers) that allows a web page to make a request to a server and get a response back without reloading the entire page. The user remains on the same page, and more important, they will not actually see the processing occur—that is, they will not see a new page loading, not by default at least. Using the XMLHttpRequest object makes it possible for a developer to alter a page previously loaded in the browser with data from the server without having to request the entire page from the server again.
What Browsers Support the XMLHttpRequest Object? XMLHttpRequest is present in Internet Explorer 5.0 and higher, Apple’s Safari 1.2 and higher, Mozilla’s Firefox 1.0 and higher, Opera 7.6 and higher, and Netscape 7 and higher. Other browsers may or may not support it, so you should check for the capability before attempting to use it if you intend to support alternative browsers. Also of note is a little JavaScript library by Andrew Gregory that allows for cross-browser Ajax support without dealing with the details of what browsers support the object and how. There are some limitations, but it is of interest nonetheless. You can find information on it here: www.scss.com.au/family/andrew/webdesign/xmlhttprequest.
479 480 APPENDIX A ■ THE XMLHTTPREQUEST OBJECT
Is the XMLHttpRequest Object a W3C Standard? (Or Any Other Kind of Standard for That Matter!) No, the XMLHttpRequest object is not a W3C standard, or a standard of any other standards body. The W3C DOM Level 3 specification’s “Load and Save” capabilities would provide similar functionality, but currently no browsers implement the Level 3 specification. Therefore, until that specification is widely adopted, if you need to send an HTTP request from a browser and get a response from a server, aside from the normal page navigation mechanism, the XMLHttpRequest object is the only viable option, along with some of the lesser-used (nowadays) alternatives like Java applets and ActiveX controls.
How Do I Use the XMLHttpRequest Object? In Mozilla, Firefox, Safari, and Netscape, you create an instance of the XMLHttpRequest object by doing the following:
For Internet Explorer:
Here is an example of using the XMLHttpRequest object:
var xhr = null; if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if (xhr) { var url = "/someURI"; xhr.onreadystatechange = xhrCallback; xhr.open("get", url, true) xhr.send() }
function xhrCallback() { if (xhr.readyState == 4) { if (xhr.status == 200) { alert("Ok"); APPENDIX A ■ THE XMLHTTPREQUEST OBJECT 481
} else { alert("Problem retrieving Ajax response"); } } }
XMLHttpRequest Object Method and Properties Reference Tables A-1 and A-2 outline the methods and properties available on the XMLHttpRequest object, representing the full API interface to that object through which you will interact with it.
Table A-1. XMLHttpRequest Object Methods Method Description abort() Stops the request that the object is currently processing. Note that like clicking the Stop button in your browser, the server will not be notified and will continue to process the request. getAllResponseHeaders This method returns all of the headers, both keys and values, as a string. getResponseHeader("key") This method returns the specified header value as a string. open("method", "url" [,asyncFlag Contrary to its name, this does not appear to literally [,"username" [,"password"]]] open anything. Instead, it just sets the parameters for the pending request. The value of method may be any valid HTTP method, get and post being the most common. asyncFlag is either true or false. Setting this to false will cause all JavaScript on the page to halt until the request returns. This is generally not desirable because if the server is unavailable, or the operation simply takes a long time, the user interface will seem to freeze to the user. Use with caution! username and password are used to make requests to URLs protected with Basic Auth security. Note that these two parameters, as well as asyncFlag, are optional, while method and url are required. send(content) This method transmits the pending request, and optionally sends a POST body or serialized DOM object (i.e., XML document). If POSTing simple parameters, content should be a string in the form “name1=value1&name2=value2”—in other words, a query string minus the initial question mark. setRequestHeader("key", "value") Sets an HTTP header that will be set on the outgoing response. 482 APPENDIX A ■ THE XMLHTTPREQUEST OBJECT
Table A-2. XMLHttpRequest Object Properties Property Description onReadyStateChange This is a pointer to the function that will serve as the event handler for the request this object instance is processing. Note that this function will be called multiple times during the lifecycle of the request. readyState This is an integer representing the status of the request. Possible values are 0 (uninitialized), 1 (loading), 2 (loaded), 3 (interactive), and 4 (complete). responseText This is a textual string version of the response from the server. Even if the response was XML, you will still find the actual text of the response here. responseXML If the response from the server was XML, the object will do the extra work of parsing it and generating a real DOM-compatible object that you can manipulate with DOM methods. status This is the numeric HTTP result code returned by the server, such as 404 if the resource is not found, or 200 if the result was OK. statusText This is a textual message string describing the status code.
XMLHttpRequest Object Status Codes Table A-3 lists the status codes that can show up in the readystate field of the XMLHttpRequest object during the lifecycle of a request as your callback function is repeatedly called.
Table A-3. XMLHttpRequest Object readystate Status Codes Numeric Code Description 0 Uninitialized. This is the value the readystate field will have initially before any operation is begun. 1 Loading. This means the open() method has been successfully called, but send() has not yet been called. 2 Loaded. This means send() has been called, and the object has completed the request, but no data has been received yet. Headers and status, however, are available at this point. 3 Receiving (or Interactive). This means the response is being chunked back to the client. responseText at this point will hold the response as received thus far. 4 Loaded (or Completed). The request has completed and the full response has been received. APPENDIX B ■ ■ ■ Libraries, Websites, and Books, Oh My!
Throughout this book, we’ve referenced a number of libraries, websites, and books for you to get further information or see examples. Here is a concise list of all those references for your convenience, even for those libraries that are used as part of an application but not specifi- cally described (but, uh, please do still read this book, OK?).
Libraries/Toolkits/Products
• Adobe (formerly Macromedia) Flash (www.adobe.com/products/flash/flashpro): Flash is not just a vector animation tool; it is truly a full-fledged development environment allow- ing you to create multimedia-rich websites that will run identically across most modern platforms (if a supported Flash player is available, which is mostly the case these days).
• Adobe (formerly Macromedia) Flex (www.adobe.com/flex): A rich client development framework that can greatly simplify creation of dynamic web applications.
• Apache Ant (ant.apache.org): The de facto standard in Java build tools.
• Apache Geronimo (geronimo.apache.org): An Apache application server.
• Apache Jakarta Commons (jakarta.apache.org/commons): Under the Commons banner you will find a number of very useful libraries, including Commons Logging, BeanUtils, FileUpload, Commons Chain, and much more. In short, if you aren’t using Commons today, you should be tomorrow!
• BEA WebLogic (www.bea.com): Another of the big players in the application server mar- ket; provides much the same capabilities as WebSphere (although both vendors have their advantages and disadvantages).
• Caucho’s Resin (www.caucho.com): Another application server, fairly popular with web hosts.
• Dojo (dojotoolkit.org): A popular Ajax toolkit that, in addition to its Ajax functionality, provides a lot of nifty client-side functions such as collections and client-side session storage, as well as a number of excellent GUI widgets.
483 484 APPENDIX B ■ LIBRARIES, WEBSITES, AND BOOKS, OH MY!
• DWR, or Direct Web Remoting (getahead.ltd.uk/dwr): A very popular Ajax library that provides a syntax in JavaScript to call objects on the server, making them appear to be running locally (in terms of the JavaScript you write).
• Eclipse (www.eclipse.org): Probably the most popular Java IDE out there, and free to boot!
• FreeMarker (freemarker.sourceforge.net): A Java-based template engine, used by default by WebWork.
• HSQLDB (www.hsqldb.org): Free, lightweight (but not in terms of functionality!), pure- Java database engine.
• IBM WebSphere (www-306.ibm.com/software/websphere): A full-blown Java application server providing many services, including servlets, JSP, JNDI, EJB, and so on.
• IntelliJ IDEA (www.jetbrains.com/idea): If you want an IDE and don’t mind paying for it, this is probably the best available.
• Java Web Parts (javawebparts.sourceforge.net): A collection of handy classes and utili- ties such as servlets, filters, taglibs, a Chain of Responsibility (CoR) implementation, and much more, to help web developers working in Java.
• jEdit (www.jedit.org): A fantastic text editor, this one is free and open source, and more important, features a large number of plug-ins that perform a great deal of tasks, bring- ing it closer to a full-blown IDE than just a text editor.
• Jetty (http://mortbay.org/jetty/index.html): Jetty is a 100 percent Java HTTP server and servlet container. This means that you do not need to configure and run a separate web server (like Apache) in order to use Java, servlets, and JSPs to generate dynamic content.
• JSLib (http://jslib.mozdev.org): A JavaScript library from the Mozilla Foundation that includes such features as an SAX XML parser.
• JSTL (java.sun.com/products/jsp/jstl): JavaServer Pages Standard Tag Library, a set of simple, common tags to be used in JSPs to make your life easier and your pages cleaner.
• Macromedia JRun (www.macromedia.com/software/jrun): Another entry in the server market.
• Maven (maven.apache.org): An increasingly popular build tool, Maven is designed to do most things for you without you having to write build scripts as you do with Ant.
• OpenEJB (http://sourceforge.net/projects/openejb): An open source, modular, con- figurable, and extendable Enterprise JavaBeans (EJB) container system and EJB server.
• Prototype (prototype.conio.net): JavaScript library for doing Ajax, as well as some other handy things.
• ROME (https://rome.dev.java.net): A Java library for working with RSS feeds.
• Sarissa (http://sourceforge.net/projects/sarissa): Billed as a general-purpose XML processing tool for JavaScript, it includes XSLT processing and much more. APPENDIX B ■ LIBRARIES, WEBSITES, AND BOOKS, OH MY! 485
• Spring Framework (www.springframework.org): A massive framework that covers a great many of the bases J2EE developers need, including an Inversion of Control (IoC) con- tainer, Aspect-Oriented Programming (AOP) support, and JDBC utility classes.
• Struts Action Framework (struts.apache.org): Perhaps the most popular web frame- work out there utilizing the Model-View-Controller (MVC) pattern.
• Tomcat (tomcat.apache.org): The reference implementation of the servlet and JSP specs, Tomcat is a fast, simple, standards-compliant, and powerful servlet container favored by many developers and hosting environments alike.
• UltraEdit (www.ultraedit.com): In my opinion, the best text editor available for Windows.
• Velocity (jakarta.apache.org/velocity): A Java-based template engine; an alternative to JSPs.
• WebWork (www.opensymphony.org/webwork): A popular MVC framework, which is, as of this writing, the future of Struts.
• Xara Webstyle (www.xara.com/products/webstyle/): For those of us who can do some graphics work but are far from artists ourselves, Webstyle is a fantastic tool to create graphics for the Web that make us look like we know what we’re doing!
• XML4Script (http://xmljs.sourceforge.net/website/documentation-w3cdom.html): Another JavaScript library for parsing XML.
Websites
• Adaptive Path (www.adaptivepath.com): The company that Jesse James Garrett works for.
• “Ajax: A New Approach to Web Applications,” by Jesse James Garrett (www.adap- tivepath.com/publications/essays/archives/000385.php): The article where Ajax got its name.
• BackBase (www.backbase.com): Providers of excellent Ajax applications and toolkits.
• CSS Zen Garden (www.csszengarden.com): If you want to see what is possible with CSS layout, look no further than this site.
• Excite (www.excite.com): A great example of a portal site.
• Flickr (www.flickr.com): Ajax-enabled photo sharing.
• Fotki (www.fotki.com): Another Ajax-enabled photo-sharing site.
• Google Maps (maps.google.com): One of the Ajax applications that brought the tech- nique to the attention of developers the world over.
• Google Suggest (www.google.com/webhp?complete=1&hl=en): Probably the most famous example of a type-ahead Ajax application. 486 APPENDIX B ■ LIBRARIES, WEBSITES, AND BOOKS, OH MY!
• Google’s GMail (gmail.google.com): One of the other great examples of Ajax usage from Google.
• Google’s RSS reader (www.google.com/reader): A web-based RSS reader from Google utilizing Ajax.
• iBiblio (www.ibiblio.org): iBiblio has a modest goal: to back up the entire Internet! Well, that might be exaggerating a bit, but it is billed as a public library and archives. Most important for the purposes of this book is the Maven repository (www.ibiblio.org/maven) they maintain, where many of the most popular open source libraries and toolkits can be downloaded automatically by Maven as well as Ant scripts.
• The JSON home page (http://json.org): All about JavaScript Object Notation (JSON).
• Mappr (www.mappr.com): An excellent example of a Flash site done well.
• MSNBC (www.msnbc.com): The website of the news channel MSNBC.
• Num Sum (www.numsum.com): An Ajax-based spreadsheet.
• OpenSymphony (http://opensymphony.com): An organization, along the lines of Apache, that supplies a number of open source products, including WebWork and XWork.
• PBase (www.pbase.com): Yes, yet another Ajax-enabled photo-sharing site.
• Prototype documentation by Sergio Pereira (www.sergiopereira.com/articles/ prototype.js.html#Enumerating).
• Shadow Gallery (www.shadowgallery.com): One of the bands I have made reference to in this book. Check them out—you’ll love them!
• Slashdot (www.slashdot.org): News for nerds, stuff that matters!
• Sun (http://java.sun.com): The place for all things Java.
• W3Schools (www.w3schools.com): An excellent all-around reference site for all things HTML. You can learn about CSS, HTML, DOM scripting, and even Ajax itself there.
• WebShots (www.webshots.com): Another Ajax-enabled photo-sharing site.
• Wikipedia (www.wikipedia.com): The free, online dictionary that everyone can help make better!
• Yahoo! (www.yahoo.com): One of the oldest search sites around; now they do just about everything.
Books
• Beginning CSS Web Development: From Novice to Professional, by Simon Collison. An excellent book to get your CSS knowledge up to snuff (Apress, 2006). APPENDIX B ■ LIBRARIES, WEBSITES, AND BOOKS, OH MY! 487
• Beginning JavaScript with Ajax and DOM Scripting: From Novice to Professional, by Chris Heilmann. A great book for JavaScript and Ajax novices, with a slightly different scope than Jeremy Keith’s book (Apress, 2006).
• Beginning XML with DOM and Ajax: From Novice to Professional, by Sas Jacobs. Another great web development book, showing how XML can be used effectively for web applications, including DOM scripting and Ajax (Apress, 2006).
• CSS Mastery, by Andy Budd, with Simon Collison and Cameron Moll. If you’re already familiar with CSS, then this book will take you up to the next level, with invaluable tech- niques and good practices (friends of ED, 2006).
• DOM Scripting:Web Design with JavaScript and the Document Object Model, by Jeremy Keith. This book will give you a good grounding in DOM scripting (friends of ED, 2005).
• Pro Ajax and Java: From Professional to Expert, by Nathaniel Schutta and Ryan Asleson. A great companion book to the one you’re reading now, this book also looks at the fusion of Java and Ajax, but from a more technology/workflow perspective rather than looking at complete projects. It covers setting up the perfect development environ- ment, testing and debugging, using Ajax libraries, and understanding the Ajax capabilities of Java frameworks such as Spring and JSF (Apress, 2006). Index
■A addPhoto() function, 293, 295 abort() method, 481 AddPhoto.java, for PhotoShare sample accessibility, 15 webapp, 303 account.js file, for The Organizer sample addPhoto.jsp file, for PhotoShare sample webapp, 339 webapp, 278 AccountAction.java, for The Organizer AddressBookManager class, 182–187 sample webapp, 346 addRoom() method, 404 accountCreate() method, 343 addRows() function, 170 accountCreate.jsp file, for The Organizer addToInventory() method, 460 sample webapp, 330 addUser() method, 385 accountCreateOK.jsp file, for The addUserToRoom() method, 389, 404 Organizer sample webapp, 330 Adobe, 483 AccountDAO.java, for The Organizer Ajax (Asynchronous JavaScript and XML) sample webapp, 343 alternatives to, 27–30 accountDelete() function, 339, 343 disadvantages of, 15 accountEdit.jsp file, for The Organizer pure, sample webapps and, 407–477 sample webapp, 332 URL for, 485 AccountObject.java, for The Organizer way of thinking and, 14 sample webapp, 341
AjaxChatDAO.java, for AjaxChat sample appointmentEdit.jsp file, for The Organizer webapp, 394–405 sample webapp, 333 ajaxError() function, 337 appointmentList.jsp file, for The Organizer AjaxReader sample application, 203–253 sample webapp, 335 client-side code for, 212–231 AppointmentObject.java, for The Organizer displayed in action, 207 sample webapp, 341 exercises for, 253 appointmentRetrieve() function, 339 server-side code for, 231–253 appointments.js file, for The Organizer structure of, 211 sample webapp, 339 ajaxRef attribute, 118 arrayIndex property, 275 ajaxRequestSender() function, 121, 134 arrays, JavaScript and, 41 AjaxTags, 27, 115, 116–121 arrow keys, 129, 132 AjaxReader sample webapp and, 204 associative arrays, 256, 412 API documentation for, 116 assureUnique variable, 375 ajaxwarrior package, 446 assureUniqueGetMessages variable, 379 ajax_config.xml file, 118 AssureUniqueUsersInRoom variable, 379 for AjaxReader sample webapp, Asynchronous JavaScript and XML. See 215–217 Ajax for Karnak sample webapp, 135–137 Atom feeds, 204 alert() pop-ups, 16 ■ altRow variable, 169 B Amazing Karnak, 115 background-color style attribute, 80 anonymous functions, JavaScript and, 48 background style attribute, 80 Ant, 84–93, 483 backslash (\), JavaScript and, 45 ant-dependencies, 90 Banfield, Steve, 14
ContactObject.java, for The Organizer custom handlers, 120 sample webapp, 341 CustomQueryString request handler, 130, contacts.js file, for The Organizer sample 136 webapp, 339 CustomQueryString.js, 124 context parameters, 100 for Karnak sample webapp, 126–134 contextInitialized() method, 296, 462 ■ ContextListener.java D for AJAX Warrior sample webapp, 462 Data Transfer Objects (DTOs), 357, for AjaxChat sample webapp, 369, 404 384–388 for The Organizer sample webapp, 340 data types, JavaScript and, 42–48 control.jsp file, for PhotoShare sample database engines, HSQLDB and, 319 webapp, 269–272 dayAtAGlance.jsp file, for The Organizer ControlEvents.js file, for PhotoShare sample webapp, 331 sample webapp, 293–296 DayAtAGlanceAction.java, for The Conversation.js file, for AJAX Warrior Organizer sample webapp, 347 sample webapp, 440 decreaseChatScrollFontSize() function,
56–61 event bubbling, 257 Find it faster at DOM manipulation methods, 66 event handlers, 119 DOM nodes, 56, 58 browsers and, 130 doMonthView() function, 340 custom, 120 doNewNote() function, 339 Dojo and, 257, 289
doPost() method, 102, 462 events, 117–120 http://superindex.apress.com/ doRedirect() method, 462 exec() method, 462 doRefreshHeadlines() function, 206, 229 BattleEnemyMoveCommand.java and, doScroller() function, 424 466 doWeekView() function, 340 Command.java and, 464 downloads EndConversationCommand.java and, Ant, 85 468 JDK, 83 SwitchWeaponCommand.java and, projects in this book, 111 472 Tomcat, 93 ToggleTalkAttackCommand.java and, doYearView() function, 340 474 drop shadows, 275 execute() method, 301, 318, 345 dsSelectorChange() function, 340 Expand Sidebar button, 226 DTOs (Data Transfer Objects), 357, Extensible Markup Language. See XML 384–388 ■ DWR (Direct Web Remoting), 144–147, 484 F dwr.xml file, InstaMail sample webapp fat clients, 5 and, 145–147 as alternative to Ajax, 30 DynaActionForm, 357–359, 369, 371, 394 FeedDescriptor DTO class, 231 feedForm, 224, 228 ■E feeds.properties file, 217, 236, 249 Eclipse, 84 filter package, 446 editContact() function, 165
Flex (Adobe), 483 GameTalkNode.java, for AJAX Warrior Flickr, 253 sample webapp, 461 float-overs, 157, 168 GameTalkReply.java, for AJAX Warrior PhotoShare sample webapp and, 272, sample webapp, 461 290 Garrett, Jesse James, 12, 485 font-family style attribute, 80 Generalized Markup Language (GML), 62 font-size style attribute, 80 Geronimo, 97, 483 font-style style attribute, 80 Getahead, 144 font-weight style attribute, 80 getAllResponseHeaders() method, 481 Form.serialize() function, 316 getAsString() method, 456