Posts Tagged 'ajax&'

Apr

23

Ajax Framework Analysis Results

Posted by kevin under ajax, internet - No Comments

Way back in January, I wrote about how my colleagues and I were evaluating Ajax frameworks to build a SOFEA-style architecture. To make our choice, we used the following process:

  1. Choose a short list of frameworks to prototype with.
  2. Create an application prototype with each framework.
  3. Document findings and create a matrix with important criteria.
  4. Create presentation to summarize document.
  5. Deliver document, presentation and recommendation.

When I wrote that entry, we had just finished step 2 and were starting step 3. I first wrote this blog post a week later, when we delivered step 5. Here is the comparison and conclusion sections of the analysis document we composed.

Framework Comparison
In order to evaluate the different frameworks against important criteria, we created a matrix with weights and ranks for each framework. This matrix shows how our weighting and rankings lead us to the winner for our project. You can view this matrix online or see below for a summary.

Note: Criteria whose values were identical across all candidates were weighted at zero. Charting capability was weighted at zero b/c we decided to use Flash for this.

This matrix indicates that GWT is the best candidate for our team to develop SOFEA-style applications with. In addition to the matrix, below are graphs that illustrate interesting (and possibly meaningless) statistics about each project.

Number of Committers

Books on Amazon

Conclusion
After working with the various frameworks, we believe that all the frameworks were very good and could be used to write applications with. If all weights are equal, these frameworks were almost even when compared against our evaluation criteria. The graph below illustrates this.

Ranking with equal criteria weights

Even after applying the weighted criteria, the evenness doesn’t change a whole lot.

Ranking with weighted criteria

Without considering the even or weighted criteria, we believe the decision all comes down to what the developers on the project feel they will be most comfortable with. If you’re developing with Dojo or YUI, chances are you’re dressing up existing HTML and possibly using progressive enhancement to add more rich functionality. On the other hand, Ext JS and GWT are similar to Swing programming where you build the UI with code (JavaScript for Ext JS, Java for GWT).

The tools available for JavaScript development have gotten increasingly better in recent years. IntelliJ IDEA has a JavaScript Editor that provides many of the same features as its Java editor. Aptana Studio also has excellent support for authoring and debugging JavaScript. However, we believe the Java debugging and authoring support in IDEs is much better. Furthermore, we are more familiar with organizing code in Java projects and feel more comfortable in this development environment.

Based on this evaluation, we believe that GWT is the best framework for our team to develop SOFEA-style applications with.

Flash Forward to Today…
The core GWT library from Google doesn’t have a whole lot of widgets, nor do they look good out-of-the-box. So early on, we experimented with two alternative implementations that continue to leverage GWT concepts and tools:

  • GXT: a GWT version of Ext JS
  • SmartGWT: a GWT version of SmartClient

Unfortunately, over the past few months, we’ve found that both of these implementations are too heavy for our requirements, mostly because of the file size of the generated JavaScript code. For example, a feature I wrote generated a 275K *.cache.html file using GXT. After determining that was too slow to give users the initial “pop”, I re-wrote it without GXT. After a day, we had an application with *.cache.html files of 133K. Yes, that’s over a 50% reduction in size!*

Because of these findings, we are proceeding with the core GWT library from Google and adding in new components as needed. It is cool to know you can make a UI “pop” with GWT, as long as you stick to the core – close-to-the-metal – components. For those applications that can afford an initial “loading…” state, I’d definitely recommend looking at GXT and SmartGWT.

* To make refactoring easier, I copied GXT MVC into our source tree and modified all imports.  (Via RaibleDesigns)

Feb

5

Ajax: The State of the Art with Dion and Ben

Posted by kevin under ajax, internet, resource, technology, web2.0 - No Comments

This morning, I added Dion and Ben’s talk titled Ajax: The State of the Art. Below are my notes from the event.

Ajax started out as a bunch of hacks. It showed that we could take our web interfaces and do a lot more with them. A hack isn’t necessarily a bad thing. Often, they turn into something much more elegant over time. The new browsers have many amazing capabilities that we haven’t taken advantage of yet. We’ve seen discussions on Ajax go from how to do XHR to frameworks and how rich and mature they are. Dojo is great for Enterprise Development (packing system, namespaces). jQuery is well-suited for lightweight developers (PHP). Prototype is fantastic for people who do a lot of JavaScript development and take it very seriously.

Today’s Ajax landscape is mature, really rich, and really exciting. Today, Dion and Ben are going to talk about technologies they’re really excited about for the future.

Canvas
The building blocks of the web are text, boxes and images. With canvas, it really makes a lot more things possible. You can do bitmap rendering and image manipulation. They’re showing a slide with Doom and Mario Kart running. Canvas 3D does true 3D rendering. Firefox and Opera have done prototypes of this. Can you do canvas-type things today in a browser? Yes, if you use Flash or Curl. Dion and Ben are excited about canvas over plugins for the following reasons:

  • No start-up delay
  • Available on mobile devices today
  • Rendering fidelity with browser (especially important for typography)
  • No bridges necessary (no marshalling/unmarshalling)
  • Not a plug-in

The <canvas> tag originally came from Apple’s Dashboard. Dashboard’s programming model was in HTML and JavaScript. Dashboard is using WebKit under the covers. Today, canvas support exists in every major browser except for IE. The good news is there are Flash and Silverlight bridges to add support to IE. There’s also an ActiveX component that wraps the Firefox implementation and allows it to run in IE.

SVG
Dion and Ben aren’t that excited about SVG because it’s such a huge spec. We’ve been struggling with the HTML standard for the last 10 years and the thought of another huge spec for the next 10 years isn’t that appealing.

Fast JavaScript
Almost all major browsers have a Fast JavaScript implementation. Chrome has V8, Safari has SquirrelFish Extreme, Firefox has TraceMonkey and Opera has Carakan. This is exciting because of industry trends and how companies are trying to reduce computation cycles in data centers. The more computing that can be put on the client, the better. IE doesn’t have anything, but Dion and Ben believe they are working on something.

Web Workers
Interface latency is awful for applications. Jakob Nielsen once said:

0.1 second is about the limit for having the user feel that the system is reacting instantaneously. 1.0 second is about the limit for the user’s flow of thought to stay uninterrupted, even though the user will notice the delay.

Anything that takes longer than a tenth of a second should be pushed to a background thread. Unfortunately, there are no threads in the web. Maybe we can add threads to JavaScript? Brendan Eich has said that “Threads suck” and there’s very little chance for threads getting into JavaScript. Gears brought Worker Pools and this is going into HTML 5 as Web Workers. You could also use Java applets to do this. With the latest Java Plugin, many of applets’ long-standing issues have been solved.

Desktop Integration
The ability to build desktop apps as web apps is very exciting. There’s a few technologies that demonstrate this: Fluid, Mozilla Prism, Adobe AIR, Appcelerator Titanium and Gears. The Palm Pre demonstrates the logical extension of this. The Palm Pre uses the web stack as its developer SDK. It’s very cool that web developers don’t have to learn anything new to become a Palm developer. Desktop integration is exciting especially if we can access desktop applications like email and address book.

The Ajax frameworks that are out there have done a lot to make web development simpler. However, there’s still a lot of pain with CSS and cross-browser issues. What if you took canvas and combined it with a sophisticated grid-based layout in JavaScript?

There’s a lot of platforms out there: Microsoft Silverlight, Adobe Flash, Apple Cocoa and Sun’s JavaFX. The web often isn’t considered a platform. Dion and Ben believe there should be an Open Web Platform. The problem right now is there is no central location to find out how to get stuff done. You have to search and find resources from many different locations. Mozilla is putting it’s resources into creating an Open Web Platform. This site will consist of 4 different areas:

  • Home
  • Documentation (for different frameworks, browsers, quirks)
  • Dashboard (state of the open web)
  • Roadmap (what’s going on)

This is not just Mozilla, it’s very much a community effort. This is something that Ben and Dion have been working on. But there’s something else they’ve been working on too. They’ve been talking about all these cool things, but what about an interesting application to test all these technologies?

Bespin
As they looked at code editors, most of them provide awful user experiences. Bespin is the Editor of Your Dreams and contains the following features:

  • Accessible from anywhere – any device in any location
  • Simple to use, like Textmate (not heavyweight like Eclipse) – an editor, not an IDE
  • Wicked Fast – performance, performance, performance
  • Rock-solid real-time collaboration, like SubEthaEdit – it just works
  • Integrated command-line, like vi – Fun like Quicksilver, social like Ubiquity
  • “Self-hosted” environment, like Emacs – For extreme extensibility, but with JavaScript!

Dion and Ben are showed a screen shot of Bespin and now they’re doing a demo. The core editor has what you’d expect with syntax highlighting and line numbers. Canvas doesn’t have text-selection by default, so they had to write it from scratch. The command line allows you to get help, run core command and also to subscribe to commands that others write. You can change your keybindings to emacs or vi as well as many other settings. Much of Bespin is event-driven, so you can easily plugin new behavior for different events.

For viewing files, they couldn’t bring themselves to use a tree. Instead, they developed a file-browsing interface that looks very much like Apple’s Finder. Personally, I like Finder, but wish it had Windows Explorer’s path bar that allows you to simply type in the path without mouse clicks. Back to the command line. They’ve done a lot to make things more discoverable so users can easily find the power of the editor.

Bespin could be used to engage developers more with open source projects. Checking out projects, modifying code and creating patches can be a real pain. Bespin could be used to interface with open source projects in the cloud. You could login, modify code and easily patch/build with the click of a button. One other thing they want to do is to have the server do code-analysis as you’re developing.

Is it OK to love a software tool? You must love your software tools. What we do as Software Developers is one of the most difficult jobs on the planet. Programmers, like poets, start with a blank slate and create something from nothing. If you don’t love your tools, you’ll start resenting what you do. If you don’t love your tools, it shows in your work. – Dave Thomas at RubyConf08

Thunderhead
A GUI Toolkit written with canvas and JavaScript. Allows you to do layouts with very little thought. It’s a lab experiment that’s in progress, stay tuned for more information.

All users care about is the user interface. Dion and Ben believe there’s a key to creating compelling user experiences. It all has to do with managing expectations. It’s not that different from how you manage relationships in your life. Expectations for movies and games have changes drastically over the years. What used to be the web (animated gifs and awful web pages) has also changed drastically (video of Apple’s online store). What was cool with MapQuest got changed drastically with Google Maps. What we have today isn’t the end of the game – expectations will continue to change. However, users have different expectations for software.

Alan Cooper has done some interesting work in this area. The software designer needs to focus in on a user’s goals. There are basic things you can apply to all users, for instance “sex sells”. An example of this is Delicious Library. This application allows you to keep track of things in your home such as books, movies, music and games. They made $500K in 3 months and made $54K the first day, with no advertising.

The quality of any software is determined by the interaction. If the interaction isn’t good, it will poison the entire experience. Donald Norman has a good quote: “Attractive things work better”. In society, this is often called “Dress for Success”.

The Open Web is hear to stay because it has:

  • An Easy Programming Model
  • Easy Remoting
  • Extensive Customization Vectors (e.g. GreaseMonkey)
  • Easy Deployment
  • Great Widgets
  • Great Visual Effects
  • Great Mobile Story
  • Desktop Integration
  • State-of-the-Art Plug-ins

Bespin is a tech preview that they hope to release next week. Thunderhead will be released at the same time.

Conclusion
This was a great talk and easily the most inspiring of the conference. Dion and Ben always do a great job and the sexiness of their presentation made it all the more appealing.

Jan

8

Choosing an Ajax Framework

Posted by kevin under internet, technology, web2.0 - No Comments

This past week, my colleagues and I have been researching Ajax Frameworks. We’re working on a project that’s following SOFEA-style architecture principles and we want the best framework for our needs. I’m writing this post to see 1) if you, the community, agree with our selection process and 2) to learn about your experiences with the frameworks we’re evaluating. Below is the process we’re following to make our choice.

  1. Choose a short list of frameworks to prototype with.
  2. Create an application prototype with each framework.
  3. Document findings and create a matrix with important criteria.
  4. Create presentation to summarize document.
  5. Deliver document, presentation (with demos) and recommendation.

For #1, we chose Ext JS, Dojo, YUI and GWT because we feel these Ajax libraries offer the most UI widgets. We also considered Prototype/Scriptaculous, jQuery and MooTools, but decided against them because of their lack of UI widgets.

For #2, we time-boxed ourselves to 3 days of development. In addition to basic functionality, we added several features (i.e. edit in place, drag and drop, calendar widgets, transitions, charts, grid) that might be used in the production application. We all were able to complete most of the functionality of the application. Of course, there’s still some code cleanup as well as styling to make each app look good for the demo. The nice thing about doing this is we’re able to look at each others code and see how the same thing is done in each framework. None of us are experts in any of the frameworks, so it’s possible we could do things better. However, I think it’s good we all started somewhat green because it shows what’s possible for someone relatively new to the frameworks.

For #3, we’re creating a document with the following outline:

Introduction

Ajax Framework Candidates
(intro and explanation)

  Project Information
  (history)
  (license / cost)
  (number of committers)
  (support options)
  (mailing list traffic (nov/dec 2008))

Matrix and Notes

Conclusion

For the Matrix referenced in the outline above, we’re using a table with weights and ranks:

Weight Criteria Dojo YUI GWT Ext JS Notes
# Important Criteria for Customer 0..1 0..1 0..1 0..1 Notes about rankings

Our strategy for filling in this matrix:

  • Customer adjusts the weight for each criteria (removing/adding as needed) so all weights add up to 1.
  • We rank each framework with 0, .5 or 1 where 0 = doesn’t satisfy criteria, .5 = partially satisfies, 1 = satisfies.

The list of criteria provided to us by our client is as follows (in no particular order).

  • Quality of Documentation/Tutorials/Self Help
  • Browser support (most important browsers/versions based on web stats)
  • Testability (esp. Selenium compatibility)
  • Licensing
  • Project health/adoption
  • Performance
  • Scalability
  • Flexibility/extensibility
  • Productivity (app dev, web dev)
  • Richness of widget/component library
  • Charting capability
  • Ability to create new widgets
  • Match to existing Java team skill-set
  • Ease of deployment (on Ops, QA, Users)
  • Degree of risk generally
  • Ability to integrate with existing site (which includes Prototype)
  • Easy to style with CSS
  • Validation (esp. marking form elements invalid)
  • Component Theme-ing/Decoration
  • CDN Availability (i.e. Google’s Ajax Libraries API or Ext CDN)

What do you think? How could this process be improved? Of course, if you have framework answers (0, .5 or 1) for our matrix, we’d love to hear your opinions. (by Matt Raible)

Feb

21

Comet: Reverse Ajax for streaming data from the server

Posted by kevin under ajax, internet, technology - No Comments

Daniel Rubio (who maintains the blogs section for TSS.com) has written an article called “Comet: Reverse Ajax for streaming data from the server,” describing ‘Comet,’ a technology to push events from the server side to a browser client. Comet manages to avoid the issues related to having a browser poll a server to check for new events.

The first thing you need to realize is that the data service on the serverside needs to be designed to hold state on behalf of browsers clients, a process that can either be very difficult or very easy, depending on the platform and language you are using. Once again, this takes us to the stateless nature of Web applications and the way a browser needs to identify itself constantly either via cookies or session IDs, or what some characterize as the Hollywood principle – “don’t call us we’ll call you” – referring that only a browser is equipped to make calls and never vice-versa.

This last issue takes us down the road of building an asynchronous server application, or if you prefer a fancier name, an HTTP-based event routing bus, or in other words, a latent application on the serverside able to keep track of clients wishing to receive updates, a design very much in line with the messaging systems used in enterprise systems that are based on publish/subscribe channels.

However, since this last mechanism represents a departure from the “bread and butter” approach used in most Web platforms, it is a big reason why most Comet applications today rely on either custom adapted application-servers or embeddable versions that can tackle these issues. In the particular case of Java, Jetty and Grizzly are two servers that currently have out-of-the box support for Comet-type designs, with varying support in other languages like Python and other popular Java servers like Tomcat, for what is technically known as “continuation support,” a paradigm by which applications are shielded from the stateless nature of the Web. Continuation support also is a touted feature of higher-level language Web frameworks written in Smalltalk and Lisp that have this capability.

Turning our attention to the client side of things, a browser can take various routes to stay in contact with these type of server applications. Among these approaches are long-polling, dynamic script tags and inclusively a workaround using IFrames, none are standard approaches by any means, which is yet another reason why many client side Comet designs rely on the use of frameworks to abstract away incompatibilities between browser implementations – similar to Ajax – with one such framework being Dojo, which in itself now serves as both an Ajax/Comet framework.

Of course, the term Comet itself is something to wonder about. AJAX’ meaning is fairly well-known, as “Asynchronous Javascript and XML,” but what about Comet?

As far as the actual term is concerned, Comet emerged as a pun to Ajax’s meaning outside IT circles as a household cleaner. But quirky name or not, Comet is serving the purpose of an umbrella name for delivering data onto browsers as it becomes available on the serverside, a technique that will surely be of the same impact and go hand in hand with what we know today as Ajax. (theserverside)

Dec

1

Beyond Ajax: Software Development, Two Years from Now

Posted by kevin under ajax, resource, technology - No Comments

Ajax has dramatically changed the lives of Web developers during the past two years, but the next two may be even more interesting. Developers—spurred by user expectations, rapidly evolving business models and ever-changing development processes—will need to do things they can’t even imagine today. And how can a forward-thinking IT department or entrepreneur—who is so dependent on innovative software developers—prepare for that future?

In a set of five articles, beginning with Beyond Ajax, CIO.com interviewed the tool builders. Their vision of the computing future will shape the tools they build, which means those are the programming tools you’ll use in a few years to build your own applications. But while CIO.com spoke with vendors, it was the techies, not the marketroids: folks like Tim Bray, Scott Guthrie, David Intersimone. Input was solicited from both vendors of proprietary software (such as Microsoft and Adobe) and open source projects (such as the Dojo Toolkit, and Open Laszlo).

Their predictions address the next round of developer opportunities, problems—and consequences. The articles cover a range of subjects, from The Convergence of Desktop, Web and Mobile Clients to UI changes (the immersive, cinematic interface) to evolving development tools which should make software development easier (what Dojo’s Alex Russell called “Interceding with the Browser gods”).

But Are Web Browsers Ready for the Next Generation of Internet Applications? Probably not, according to Tim Bray, who said, “The people who make a living building Web apps and tools for them live on a different planet than the people who build browsers.” All those problems… er, challenges were packaged up and handed to the folks who run Mozilla and IE, and the Browser dudes responded about making the Internet trustworthy, standards-compatible and innovative.

What kinds of developer tools would you like to see a few years from now? What are the toughest developer pain points you’d like tool vendors to address?

Nov

16

AJAX Google Pagerank Tool

Posted by kevin under ajax, resource - No Comments

InstantPageRanker.com is designed to give webmasters and web marketing professionals an SEO tool to instantly determine a website’s Google PageRank.

Type a website address in the box below to see the pagerank instantly (ie. www.tmtbox.com or tmtbox.com).

Nov

16

20+ Tools For Working With AJAX

Posted by kevin under resource - No Comments
    ajaxtools1.PNG

AJAX may be an overused buzzword, but it also has some incredibly cool uses within your websites. We’ve rounded up the best AJAX tools for your perusal – free feel to add more suggestions in the comments.

    AJAX indicators

AJAX Activity Indicators – A large collection of animated GIFs for you to use as your AJAX application’s progress indicator.

    AJAX For N00bs

AJAX For N00bs – Just as the site name implies, a site to help people just beginning to learn AJAX.

    AJAX Mistakes

AJAX Mistakes – An editable list of common mistakes developers make when implementing AJAX, and suggestions on how to avoid them yourself.

    AJAXFreaks.com

AJAXFreaks.com – A collection of scripts, tutorials, forums and more.

    AJAXload.info

AJAXload.info – If you can’t find the perfect AJAX load icon for your project, this site will help you generate one to meet your needs.

    Backbase.com

Backbase.com – An enterprise-level AJAX development platform with numerous pre-built widgets.

    Clean AJAX

Clean AJAX – A Sourceforge project for a Javascript, Server Side, AJAX framework.

    dhtmlsite.com

dhtmlsite.com – Tons of tutorials for AJAX developers of all skill levels.

    Google AJAX API

Google AJAX API – The Google API will help you implement Google services on your web page while utilizing AJAX page loading.

    Google AJAX toolkit

Google Web Toolkit – A Google-produced tool to help you become less accident-prone when writing AJAX apps.

    jquery.com

jQuery.com – A JavaScript library built to work with AJAX; super slick on their front page.

    LoadInfo.net

LoadInfo.net – Customizable AJAX loading animated GIFs that are free to use.

    MiniAJAX.com

MiniAJAX.com – A large collection of downloadable AJAX scripts, most of which are configurable.

    prototypejs.org

Prototypejs.org – A JavaScript framework that includes an AJAX library and aims to make app building easier.

    qooxdoo.org

Qooxdoo.org – An open source AJAX development framework with JavaScript development and a rich GUI.

    Rialto

Rialto – A cross-platform, corporate web applications driven framework.

    SAJAX

SAJAX – A framework for calling PHP, Perl or Python from your pages without refreshing the browser.

    script.acul.us

script.acul.us – Works with Prototype, works heavily on AJAX in interfaces.

    sergiopereira AJAX

Sergiopereira.com AJAX Articles – A large collection of tutorials and code snippets to help you learn AJAX.

    ThinWire

ThinWire.com – A Java tool to help you build AJAX apps with a GUI Desktop feel to them.

    Yahoo User Interface

Yahoo User Interface Library – Yahoo’s attempt at helping you build AJAX driven apps.

Nov

16

Getting Started with Ajax

Posted by kevin under ajax - 1 Comment

The start of 2005 saw the rise of a relatively new technology, dubbed “Ajax” by Jesse James Garrett of Adaptive Path. Ajax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the nonstandard XMLHttpRequest() object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including XML, HTML, and even text files. Ajax’s most appealing characteristic, however, is its “asynchronous” nature, which means it can do all of this without having to refresh the page. This allows you to update portions of a page based upon user events and provides one of the cornerstones of Rich Internet Applications (RIA) referred to in discussions of “Web 2.0.”

The DOM plays into Ajax in a number of ways. How you use the DOM depends a good deal on how you handle the content returned from the server. You can treat the con­tent as simple text using the responseText property of the server response, or you can treat it as XML using responseXML. Assuming the content you pull back from the server is an (X)HTML snippet and you’ve gotten it as responseText, you could drop that content into a particular spot on the page using innerHTML. On the flip side, if the content you pull back is XML and you’ve gotten it as responseXML, you can traverse its DOM, cherry-picking or performing functions on the elements, attributes, and text nodes.This probably sounds very confusing, but it is pretty easy once we go over a few simple examples. For these examples, we are using the XHConn library for simplifying our interaction with XMLHttpRequest(). The XHConn library is freely available at xkr.us/code/javascript/XHConn/ and allows simple access to XMLHttpRequest() by creating a new XHConn object and then initiating its connect() method as you will soon see.

As with the DOM Scripting examples (above), for a blow-by-blow of what the script is doing, read the JavaScript comments.

Example 1: Ajax with innerHTML

For a simple innerHTML-based Ajax example, we’ll create a quasi-functional address book application. We’ll start with the XHTML page (line wraps marked » —Ed.):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" »
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" »
  xml:lang="en" lang="en">
<head>
  <title>Ajax Address Book</title>
  <meta http-equiv="content-type" content="text/html; »
    charset=iso-8859-1" />
  <meta http-equiv="Content-Language" content="en-us" />
  <script type="text/javascript" src="XHConn.js"></script>
  <script type="text/javascript" src="addressBook.js"></script>
</head>
<body>
  <h1>Simple Ajax Address Book</h1>
  <form action="getAddress.php" method="POST">
    <fieldset>
      <legend>Please Choose a Person</legend>
      <select id="person" name="person">
        <option value="">Choose Someone</option>
        <option value="1">Bob Smith</option>
        <option value="2">Janet Jones</option>
      </select>
      <input type="submit" id="submit" name="submit" »
        value="Get the Address" />
    </fieldset>
  </form>
  <pre id="address"></pre>
</body>
</html>

As you can see, we have a simple form with a select, from which to choose a person. Again, we are providing a fallback action for the form, in case our JavaScript cannot run. Below the form, we have a simple pre element that will be displaying the address information from the database.

And now for the JavaScript. Basically, we will be commandeering the select and using its onchange event handler to trigger an XMLHttpRequest() call to obtain the address information for the selected individual. The server will be returning this information as a string like this:

Bob Smith
123 School Street
Anytown, NY 12345

We will take this return as a string and dump it into the pre element using innerHTML. Take a look at the code (line wraps marked » —Ed.):

var addressBook = {
  myConn:      false, // the XMLHttpRequest
  body:        false, // the body element
  target:      false, // the target container
  loader:      false, // the loader
  init:        function(controlId, sbmtBtnId, targetId){
    /* init() takes three arguments:
       * the id of the controller (select)
       * the id of the submit button
       * the id of the target container */
    // test for methods & elements
    if(!document.getElementById ||
       !document.getElementsByTagName ||
       !document.getElementById(controlId) ||
       !document.getElementById(sbmtBtnId)  ||
       !document.getElementById(targetId)) return;
    // set and test XHConn, quitting silently if it fails
    addressBook.myConn = new XHConn();
    if(!addressBook.myConn) return;
    // get the body
    addressBook.body = document.getElementsByTagName('body')[0];
    // get the controller
    var control = document.getElementById(controlId);
    // get the submit button
    var sbmtBtn = document.getElementById(sbmtBtnId);
    // remove the submit button
    sbmtBtn.parentNode.removeChild(sbmtBtn);
    // get the target
    addressBook.target = document.getElementById(targetId);
    // add the onchange event to the controller,
    addressBook.addEvent(control,
                         'change',
                         function(){
                           if(this.value != ''){
                             /* if there's a value,
                                trigger getAddress */
                             addressBook.getAddress(this.value);
                           } else {
                             // otherwise empty the target
                             addressBook.target.innerHTML = '';
                           }
                         });
  },
  getAddress:  function(id){ // the Ajax call
    // let's let the user know something is happening (see below)
    addressBook.buildLoader();
    /* this is the function that is run
       once the Ajax call completes */
    var fnWhenDone = function(oXML) {
      // get rid of the loader
      addressBook.killLoader();
      // insert the returned address information into the target
      addressBook.target.innerHTML = oXML.responseText;
    };
    // use XHConn's connect method
    addressBook.myConn.connect('index.php', 'POST',
                               'id='+id, fnWhenDone);
  },
  buildLoader: function(){     // builds a loader
    // create a new div
    addressBook.loader = document.createElement('div');
    // give it some style
    addressBook.loader.style.position   = 'absolute';
    addressBook.loader.style.top        = '50%';
    addressBook.loader.style.left       = '50%';
    addressBook.loader.style.width      = '300px';
    addressBook.loader.style.lineHeight = '100px';
    addressBook.loader.style.margin     = '-50px 0 0 - 150px';
    addressBook.loader.style.textAlign  = 'center';
    addressBook.loader.style.border     = '1px solid #870108';
    addressBook.loader.style.background = '#fff';
    // give it some text
    addressBook.loader.appendChild( »
      document.createTextNode( »
        'Loading Data, please waitu2026'));
    // append it to the body
    addressBook.body.appendChild(addressBook.loader);
  },
  killLoader:  function(){     // kills the loader
    // remove the loader form the body
    addressBook.body.removeChild(addressBook.loader);
  },
  addEvent: function(obj, type, fn){  // the add event function
    if (obj.addEventListener) »
      obj.addEventListener(type, fn, false);
    else if (obj.attachEvent) {
      obj["e"+type+fn] = fn;
      obj[type+fn] = function() {
        obj["e"+type+fn](window.event);
      };
      obj.attachEvent("on"+type, obj[type+fn]);
    }
  }
};
/* run the init() method on page load, passing it
   the required arguments */
addressBook.addEvent(window, 'load',
                     function(){
                       addressBook.init('person',
                                        'submit',
                                        'address');
                     });

See this script in action.

Example 2: Ajax with Nodes

Let’s alter the example, and instead of returning a string from the server, this time, make it XML:

<file>
  <name>
    <first>Bob</first>
    <last>Smith</last>
  </name>
  <address>
    <street>123 School Street</street>
    <city>Anytown</city>
    <state>NY</state>
    <zip>12345</zip>
  </address>
</file>

The XHTML page remains the same, but we need to make some minor adjustments to the JavaScript. To highlight the differences, I will touch on each change individually.

The first change, to the onchange event handler of the select, is pretty simple (line wraps marked » —Ed.):

…
    addressBook.addEvent(addressBook.control,
                         'change',
                         function(){
                            if(this.value != ''){
                              addressBook.getAddress(this.value);
                           } else {
                             addressBook.target.removeChild( »
                               addressBook.target.firstChild);
                           }
                         });
…

Instead of setting the content of the target to empty using innerHTML, the DOM is removing the node that is the target’s first child.

Next up is the getAddress() method (line wraps marked » —Ed.):

…
  getAddress:  function(id){
    addressBook.buildLoader();
    var fnWhenDone = function(oXML) {
      addressBook.killLoader();
      if(addressBook.target.hasChildNodes()){
        addressBook.target.removeChild( »
          addressBook.target.firstChild);
      }
      xml = oXML.responseXML;
      var name    = addressBook.getNodeValue(xml, 'first')+' '+
                    addressBook.getNodeValue(xml, 'last');
      var address = addressBook.getNodeValue(xml, 'street');
      var csz     = addressBook.getNodeValue(xml, 'city')+', '+
                    addressBook.getNodeValue(xml, 'state')+' '+
                    addressBook.getNodeValue(xml, 'zip');
      var txt = document.createTextNode(name + " n" +
                                        address + "n" + csz);
      addressBook.target.appendChild(txt);
    };
    addressBook.myConn.connect('getAddress.php', 'POST',
                               'id=' + id, fnWhenDone);
  },
…

As we are working with XML, we can use the responseXML property to get the return from the server as a node tree. Then we can traverse that tree, collecting the tidbits of information we need. In this example, we added a new method (getNodeValue()) that makes working with XML returns easier:

…
  getNodeValue: function(tree, el){
    return tree.getElementsByTagName(el)[0].firstChild.nodeValue;
  },
…

This method takes two arguments: the node tree (tree) and the element (el) whose content is wanted. It returns the nodeValue of the firstChild of the first el within tree or, in other words, the text value of the node requested from the node tree.

Once we have collected all of the requested contents from the XML, the text string is rebuilt and generated with the DOM before being appended to the target. The end result can be seen here.

You may be wondering, why do both examples do the exact same thing? It shows how you can work with two completely different backend systems and still get the results you want. In Ajax, as in many things, flexibility is important to get the job done.

Want to read more?

Web Design in a Nutshell, by Jennifer Niederst Robbins and featuring contributions from Darek Featherstone and Aaron Gustafson, has been completely rewritten to reflect the best practices of the web standards world and is on shelves now.

Ajax Resources

For more information on Ajax, consult:

About the Author

 Aaron Gustafson ALA technical editor Aaron Gustafson is the founder and principal consultant at Easy Designs, a web development boutique. He writes and speaks often on the various layers of the web standards cake, and works to improve the usability and accessibility of the web.

Nov

15

Open Ajax Alliance Member

Posted by kevin under ajax, resource - 1 Comment

The goal of Open Ajax is to make the delivery of rich Ajax user interfaces substantially easier than it has been for solutions. At the same time, the Open Ajax Alliance seeks to ensure that there is a compelling Ajax platform that remains independent of

  • Client browser, operating system, and device/hardware
  • Server container/language (Java, PHP, Ruby, C#, etc.), operating system, and hardware

Participants in the Open Ajax Alliance see collaboration through existing open source communities as our best means to preserve the multi-client, multi-server value proposition of the World-wide Web as we deliver richer user interfaces via Ajax and other Web 2.0 technologies.

At the same time, Open Ajax will support other Ajax runtimes, such as the Dojo Toolkit, in addition to Kabuki. The goal is to get a handful of open source Ajax toolkit runtimes to critical mass and ensure they are each well integrated with Eclipse and Mozilla technologies (Think SWT and Swing from the Java days).

Nov

15

Top 10 Ajax Applications

Posted by kevin under resource - 1 Comment

1. Kiko. A general purpose online calendar. Elegant interface and design. API coming soon.

2. Backbase’s RSS Reader. Only a demo, so you can’t add your own feeds. Still, very nice.

3. Backpack. To do list organizer and simple project management application. Includes email and mobile reminders.

4. Writely. Online word processor. A bit rough around the edges (you can’t save in MSF T Word format, for example) but still feels like a real application. Update: per Sam Schillace @ Writely, you can export in Word format (ed: sorry for missing this). Also, API and blog publishing features coming soon.

5. Amazon Zuggest. Francis Shanahan’s version of Google Suggest–but for Amazon.

6. TimeTracker. Personal time management tool.

7. Del.icio.us Director. Rich UI for managing your del.icio.us links.

8. Backbase’s Information Portal. A highly interactive aggregation page.

9. Protopage. Another twist on an information portal.

10. Periodic Table of the Elements. The next must-have for high school chemistry students?