Q.What Is Ajax?
Ans: AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many web developers until recently when applications such as Gmail, Google Suggest, and Google Maps hit the streets. Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates: * standards-based presentation using XHTML and CSS; * dynamic display and interaction using the Document Object Model; * data interchange and manipulation using XML and XSLT; * Asynchronous data retrieval using XMLHttpRequest; * JavaScript binding everything together.Q.Who Is Using Ajax?Ans: Google is making a huge investment in developing the Ajax approach. All of the major products Google has introduced over the last year like Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps are Ajax applications. (For more on the technical nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon’s A9.com search engine applies similar techniques. These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn’t another technology that only works in a laboratory. Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps. At Adaptive Path, we’ve been doing our own work with Ajax over the last several months, and we’re realizing we’ve only scratched the surface of the rich interaction and responsiveness that Ajax applications can provide. Ajax is an important development for Web applications, and its importance is growing. The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. As there are so many developers out there who already know how to use these technologies, we expect to see many more organizations following Google’s lead in reaping the competitive advantage Ajax provides. The challenges are for the designers of these applications to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilitiesQ.How Ajax Is Different?Ans: An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something. The synchronous interaction pattern of a traditional web application (top) compared with the asynchronous pattern of an Ajax application (bottom). Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. Any response to a user action that doesn’t require a trip back to the server such as simple data validation, editing data in memory, and even some navigation the engine handles on its own. If the engine needs something from the server in order to respond if it’s submitting data for processing, loading additional interface code, or retrieving new data the engine makes those requests asynchronously, usually using XML, without stalling a user’s interaction with the application.Q.Where Should I Start?Ans: Assuming the framework you are using does not suffice your use cases and you would like to develop your own AJAX components or functionality I suggest you start with the article Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition. If you would like to see a very basic example that includes source code you can check out the tech tip Using AJAX with Java Technology. For a more complete list of AJAX resources the Blueprints AJAX Home page.Next, I would recommend spending some time investigating AJAX libraries and frameworks. If you choose to write your own AJAX clients-side script you are much better off not re-inventing the wheel. AJAX in Action by Dave Crane and Eric Pascarello with Darren James is good resource. This book is helpful for the Java developer in that in contains an appendix for learning JavaScript for the Java developer.Q.Do Ajax Applications Always Deliver A Better Experience Than Traditional Web Applications?Ans: Not necessarily. Ajax gives interaction designers more flexibility. However, the more power we have, the more caution we must use in exercising it. We must be careful to use Ajax to enhance the user experience of our applications, not degrade it.Q.Are Ajax Applications Easier To Develop Than Traditional Web Applications?Ans: Not necessarily. Ajax applications inevitably involve running complex JavaScript code on the client. Making that complex code efficient and bug-free is not a task to be taken lightly, and better development tools and frameworks will be needed to help us meet that challenge.Q.Does Ajax Work With Java?Ans: Absolutely. Java is a great fit for AJAX! You can use Java Enterprise Edition servers to generate AJAX client pages and to serve incoming AJAX requests, manage server side state for AJAX clients, and connect AJAX clients to your enterprise resources. The JavaServer Faces component model is a great fit for defining and using AJAX components.Q.Do I Really Need To Learn Javascript?Ans: Basically yes if you plan to develop new AJAX functionality for your web application. On the other hand, JSF components and component libraries can abstract the details of JavaScript, DOM and CSS. These components can generate the necessary artifacts to make AJAX interactions possible. Visual tools such as Java Studio Creator may also use AJAX enabled JSF components to create applications, shielding the tool developer from many of the details of AJAX. If you plan to develop your own JSF components or wire the events of components together in a tool it is important that you have a basic understanding of JavaScript. There are client-side JavaScript libraries (discussed below) that you can call from your in page JavaScript that abstract browser differences. Object Hierarchy and Inheritance in JavaScript is a great resource for a Java developer to learn about JavaScript objects.Q.Won't My Server-side Framework Provide Me With Ajax?Ans: You may be benefiting from AJAX already. Many existing Java based frameworks already have some level of AJAX interactions and new frameworks and component libraries are being developed to provide better AJAX support. I won't list all the Java frameworks that use AJAX here, out of fear of missing someone, but you can find a good list at www.ajaxpatterns.org/Java_Ajax_Frameworks. If you have not chosen a framework yet it is recommended you consider using JavaServer Faces or a JavaServer Faces based framework. JavaServer Faces components can be created and used to abstract many of the details of generating JavaScript, AJAX interactions, and DHTML processing and thus enable simple AJAX used by JSF application developer and as plug-ins in JSF compatible IDE's, such as Sun Java Studio Creator.Q.Did Adaptive Path Invent Ajax? Did Google? Did Adaptive Path Help Build Google's Ajax Applications?Ans: Neither Adaptive Path nor Google invented Ajax. Google’s recent products are simply the highest-profile examples of Ajax applications. Adaptive Path was not involved in the development of Google’s Ajax applications, but we have been doing Ajax work for some of our other clients.Q.Is It Possible To Set Session Variables From Javascript?Ans: It's not possible to set any session variables directly from javascript as it is purely a client side technology. You can use AJAX though to asynchronously...Q.Cannot Parse Xml Generated By Jsp I Am Generating An Xml Using Jsp, When I Run The Jsp In Ie It Shows The Xml As Per Dom, But When I Try To Parse It Using Javascript , The Command Xmldoc.documentelement ?Ans: This is working code, it might help you. if (!isIE) xmldoc = req.responseXML; else { //IE does not take the responseXML as.Q.What Do I Need To Know To Create My Own Ajax Functionality?Ans: If you plan not to reuse and existing AJAX component, here are some of the things you will need to know.
- Plan to learn Dynamic HTML (DHTML), the technology that is the foundation for AJAX. DHTML enables browser-base real time interaction between a user and a web page. DHTML is the combination of JavaScript, the Document Object Model (DOM) and Cascading Style Sheets (CSS).
- JavaScript - JavaScript is a loosely typed object based scripting language supported by all major browsers and essential for AJAX interactions. JavaScript in a page is called when an event in a page occurs such as a page load, a mouse click, or a key press in a form element.
- DOM - An API for accessing and manipulating structured documents. In most cases DOM represent the structure of XML and HTML documents.
- CSS - Allows you to define the presentation of a page such as fonts, colors, sizes, and positioning. CSS allow for a clear separation of the presentation from the content and may be changed programmatically by JavaScript.
Understanding the basic request/response nature of HTTP is also important. Many subtle bugs can result if you ignore the differences between the GET and OIst methods when configuring an XMLHttpRequest and HTTP response codes when processing callbacks. JavaScript is the client-side glue, in a sense. JavaScript is used to create the XMLHttpRequest Object and trigger the asynchronous call. JavaScript is used to parse the returned content. JavaScript is used to analyze the returned data and process returned messages. JavaScript is used to inject the new content into the HTML using the DOM API and to modify the CSS.Q.What Javascript Libraries And Frameworks Are Available?Ans: There are many libraries/frameworks out there (and many more emerging) that will help abstract such things as all the nasty browser differences. Three good libraries are The Dojo Toolkit, Prototype, and DWR.
- The Dojo Toolkit contains APIs and widgets to support the development of rich web applications. Dojo contains an intelligent packaging system, UI effects, drag and drop APIs, widget APIs, event abstraction, client storage APIs, and AJAX interaction APIs. Dojo solves common usability issues such as support for dealing with the navigation such as the ability to detect the browser back button, the ability to support changes to the URL in the URL bar for bookmarking, and the ability to gracefully degrade when AJAX/JavaScript is not fully support on the client. Dojo is the Swiss Army Knife of JavaScript libraries. It provides the widest range of options in a single library and it does a very good job supporting new and older browsers.
- Prototype focuses on AJAX interactions including a JavaScript AJAX object that contains a few objects to do basic tasks such as make a request, update a portion of a document, insert content into a document, and update a portion of a document periodically. Prototype JavaScript library contains a set of JavaScript objects for representing AJAX requests and contains utility functions for accessing in page components and DOM manipulations. Script.aculo.us and Rico are built on top of Prototype and provide UI effects, support for drag and drop, and include common JavaScript centric widgets. If you are just looking to support AJAX interactions and a few basic tasks Prototype is great. If you are looking for UI effects Rico and Script.aculo.us are good options.
- DWR (Dynamic Web Remoting) is a client-side and server-side framework that focuses on allowing a developer to do RPC calls from client-side JavaScript to plain old Java objects in a Java Enterprise Edition web container. On the server side DWR uses a Servlet to interact with the Java objects and returns object representations of the Java objects or XML documents. DWR will be easy to get up and running and plays well with other Java technologies. If you are looking for a client-side and server-side framework that integrates well use DWR.
There are many new and emerging libraries for JavaScript and this list only reviews some of the more common libraries. When making a choice choose the library which suites your needs the best. While it might be better to choose one, there is nothing stopping you from using more than one framework. For a more extensive list of client-side frameworks see: Survey of AJAX/JavaScript Libraries.Q.What Is The Difference Between Proxied And Proxyless Calls?Ans: Proxied calls are made through stub objects that mimic your PHP classes on the JavaScript side. E.g., the helloworld class from the Hello World example. Proxyless calls are made using utility javascript functions like HTML_AJAX.replace() and HTML_AJAX.append().Q.Should I Use Xml Or Text, Javascript, Or Html As A Return Type?Ans: It depends. Clearly the 'X' in AJAX stands for XML, but several AJAX proponents are quick to point out that nothing in AJAX, per se, precludes using other types of payload, such as, JavaScript, HTML, or plain text.
- XML - Web Services and AJAX seem made for one another. You can use client-side API's for downloading and parsing the XML content from RESTful Web Services. (However be mindful with some SOAP based Web Services architectures he payloads can get quite large and complex, and therefore may be inappropriate with AJAX techniqes.)
- Plain Text - In this case server-generated text may be injected into a document or evaluated by client-side logic.
- JavaScript - This is an extension to the plain text case with the exception that a server-side component passes a fragment of JavaScript including JavaScript object declarations. Using the JavaScript eval() function you can then create the objects on the client. JavaScript Object Notation (JSON), which is a JavaScript object based data exchange specification, relies on this technique.
- HTML - Injecting server-generated HTML fragments directly into a document is generally a very effective AJAX technique. However, it can be complicated keeping the server-side component in sync with what is displayed on the client.
Mashup is a popular term for creating a completely new web application by combining the content from disparate Web Services and other online API's. A good example of a mashup is housingmaps.com which graphically combines housing want-ads from craiglist.org and maps from maps.google.com.Q.Are There Usability Issues With Ajax?Ans: The nature of updating a page dynamically using data retrieved via AJAX interactions and DHTML may result in drastically changing the appearance and state of a page. A user might choose to use the browser's back or forward buttons, bookmark a page, copy the URL from the URL bar and share it with a friend via an email or chat client, or print a page at any given time. When designing an AJAX based application you need to consider what the expected behavior would be in the case of navigation, bookmarking, printing, and browser support as described below.
- Navigation -What would be the expected behavior of the back, forward, refresh, and bookmark browser buttons in your application design. While you could implement history manipulation manually it may be easer to use a JavaScript frameworks such as Dojo that provides API's history manipulation and navigation control.
- Bookmarking and URL sharing -Many users want to bookmark or cut and paste the URL from the browser bar. Dojo provides client-side for bookmarking and URL manipulation.
- Printing - In some cases printing dynamically rendered pages can be problematic.
Other considerations as a developer when using AJAX are:
- Browser Support - Not all AJAX/DHTML features are supported on all browsers or all versions of a browser. See quirksmode.org for a list of browser support and possible workarounds.
- JavaScript disabled -You should also consider what happens if the user disables JavaScript. Additionally, there are several legitimate reasons why JavaScript and CSS support may be unavailable on a user's web browser.
- Latency -Keep in mind latency in your design. A running application will be much more responsive than when it is deployed. Latency problems: myth or reality?
- Accessibility -Guaranteeing your site is accessible to people with disabilities is not only a noble goal, it is also requited by law in many markets. Some marvelous enabling technology is available to help people use the Web in spite of disabilities including visual, auditory, physical, speech, cognitive, and neurological disabilities. With a little forethought, and comprehension of some well documented best practices, you can assure that your application is compatible with that enabling technology.
Degradability is the term used to describe techniques used by web applications to adapt to the wide range of web browser capabilities. Many AJAX libraries have automatic degradability built in. But if you are coding your own custom AJAX functionality, simply taking some care to follow the best practices promoted by standards bodies like the World Wide Web Consortium (W3C), and grass root movements like the Web Standards community and many others, your application can run usefully on browsers that are incapable of AJAX behaviors. Granted, your application may loose some of the "wow factor" on these less capable browsers, but your application will still be usable. Remember to not design with AJAX just for the sake of coolness. The reason you built your application is so people will use it. And people will not use your application if your application is not compatible with their web browser.Q.Are There Any Frameworks Available To Help Speedup Development With Ajax?Ans: There are several browser-side frameworks available, each with their own uniqueness...Q.Is Adaptive Path Selling Ajax Components Or Trademarking The Name? Where Can I Download It?Ans: Ajax isn’t something you can download. It’s an approach — a way of thinking about the architecture of web applications using certain technologies. Neither the Ajax name nor the approach is proprietary to Adaptive Path.Q.Should I Use An Http Get Or Post For My Ajax Calls?Ans: AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idempotency recommendations and is highly recommended for consistent web application architecture.Q.How Do We Debug Javascript?Ans: There are not that many tools out there that will support both client-side and server-side debugging. I am certain this will change as AJAX applications proliferate. I currently do my client-side and server-side debugging separately. Below is some information on the client-side debuggers on some of the commonly used browsers.
- Firefox/Mozilla/Netscape - Have a built in debugger Venkman which can be helpful but there is a Firefox add on known as FireBug which provides all the information and AJAX developer would ever need including the ability to inspect the browser DOM, console access to the JavaScript runtime in the browser, and the ability to see the HTTP requests and responses (including those made by an XMLHttpRequest). I tend to develop my applications initially on Firefox using Firebug then venture out to the other browsers.
- Safari - Has a debugger which needs to be enabled. See the Safari FAQ for details.
- Internet Explorer - There is MSDN Documentation on debugging JavaScript. A developer toolbar for Internet Explorer may also be helpful.
While debuggers help a common technique knowing as "Alert Debugging" may be used. In this case you place "alert()" function calls inline much like you would a System.out.println. While a little primitive it works for most basic cases. Some frameworks such as Dojo provide APIs for tracking debug statements.Q.How Do I Provide Internationalized Ajax Interactions?Ans: Just because you are using XML does not mean you can properly send and receive localized content using AJAX requests. To provide internationalized AJAX components you need to do the following: Step 1. Set the charset of the page to an encoding that is supported by your target languages. I tend to use UTF-8 because it covers the most languages. The following meta declaration in a HTML/JSP page will set the content type: Step 2.In the page JavaScript make sure to encode any parameters sent to the server. JavaScript provides the escape() function which returns Unicode escape strings in which localized text will appear in hexadecimal format. For more details on JavaScript encoding seeComparing escape(), encodeURI(), and encode URI Component(). Step 3. On the server-side component set the character encoding using the HttpServletRequest.setCharacterEncoding() method. Before you access the localized parameter using the HttpServletRequest.getParameter() call. In the case of UTF this would be request .set Characther Encoding ("UTF-8");. A server-side component returning AJAX responses needs to set the encoding of the response to the same encoding used in the page. response.setContentType("text/xml;charset=;UTF-8"); response.getWriter().write(" invalid "); For more information on using AJAX with Java Enterprise Edition technologies see AJAX and Internationalization and for developing multi-lingual applications see Developing Multilingual Web Applications Using JavaServer Pages Technology.Q.Some Of The Google Examples You Cite Don't Use Xml At All. Do I Have To Use Xml And/or Xslt In An Ajax Application?Ans: No. XML is the most fully-developed means of getting data in and out of an Ajax client, but there’s no reason you couldn’t accomplish the same effects using a technology like JavaScript Object Notation or any similar means of structuring data for interchange.Q.When Do I Use A Synchronous Versus Asynchronous Request?Ans: They don't call it AJAX for nothing! A synchronous request would block in page event processing and I don't see many use cases where a synchronous request is preferable.Q.How Do I Handle Concurrent Ajax Requests?Ans: With JavaScript you can have more than one AJAX request processing at a single time. In order to insure the proper post processing of code it is recommended that you use JavaScript Closures. The example below shows an XMLHttpRequest object abstracted by a JavaScript object called AJAXInteraction. As arguments you pass in the URL to call and the function to call when the processing is done. function AJAXInteraction(url, callback) { var req = init(); req.onreadystatechange = processRequest; unction init() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } } function processRequest () { if (req.readyState == 4) { if (req.status == 200) { if (callback) callback(req.responseXML); } } } this.doGet = function() { req.open("GET", url, true); req.send(null); } this.doPost = function(body) { req.open("POST", url, true); req.setRequestHeader("Content-Type", " application/x-www-form-urlencoded"); req.send(body); } } function makeRequest() { var ai = new AJAXInteraction("processme", function() { alert("Doing Post Process");}); ai.doGet(); } The function makeRequest() in the example above creates an AJAXInteraction with a URL to of "processme" and an inline function that will show an alert dialog with the message "Doing Post Process". When ai.doGet() is called the AJAX interaction is initiated and when server-side component mapped to the URL "processme" returns a document which is passed to the callback function that was specified when the AJAXInteraction was created. Using this closures insures that the proper callback function associated with a specific AJAX interaction is called. Caution should still be taken when creating multiple closure objects in that make XmlHttpRequests as to there is a limited number of sockets that are used to make requests at any given time. Because there are limited number of requests that can be made concurrently. Internet Explorer for example only allows for two concurrent AJAX requests at any given time. Other browsers may allow more but it is generally between three and five requests. You may choose to use pool of AJAXInteraction objects. One thing to note when making multiple AJAX calls from the client is that the calls are not guaranteed to return in any given order. Having closures within the callback of a closure object can be used to ensure dependencies are processed correctly. There is a discussion titled Ajaxian Fire and Forget Pattern that is helpful.Q.What Do I Do On The Server To Interact With An Ajax Client?Ans: The "Content-Type" header needs to be set to"text/xml". In servlets this may be done using the HttpServletResponse.setContentType()should be set to "text/xml" when the return type is XML. Many XMLHttpRequest implementations will result in an error if the "Content-Type" header is set The code below shows how to set the "Content-Type". response.setContentType("text/xml"); response.getWriter().write("invalid"); You may also want to set whether or not to set the caches header for cases such as autocomplete where you may want to notify proxy servers/and browsers not to cache the results. response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("invalid"); Note to the developer: Internet Explorer will automatically use a cached result of any AJAX response from a HTTP GET if this header is not set which can make things difficult for a developer. During development mode you may want set this header. Where do I store state with an AJAX client As with other browser based web applications you have a few options which include:
- On the client in cookies - The size is limited (generally around 4KB X 20 cookies per domain so a total of 80KB) and the content may not be secure unless encrypted which is difficult but not impossible using JavaScript.
- On the client in the page - This can be done securely but can be problematic and difficult to work with. See my blog entry on Storing State on the Client for more details on this topic.
- On the client file system - This can be done if the client grants access to the browser to write to the local file system. Depending on your uses cases this may be necessary but caution is advised.
- On the Server - This is closer to the traditional model where the client view is of the state on the server. Keeping the data in sync can be a bit problematic and thus we have a solution Refreshing Data on this. As more information processing and control moves to the client where state is stored will need to be re-evaluated.
Q.Whats With The -alpha In The Install Instructions?Ans: HTML_AJAX hasn't had a stable release yet and the pear installer doesn't install non stable packages by default unless you specify a version.Q.How Do I Submit A Form Or A Part Of A Form Without A Page Refresh?Ans: When creating a form make sure that the "form" element "onSubmit" attribute is set to a JavaScript function that returns false.
No comments:
Post a Comment