Vous êtes sur la page 1sur 36

AJAX – IMPROVING THE CUSTOMER EXPERIENCE

.":70-6.&*446&…888"+"94:4$0/$0.

pushing

into high gear


1-64
)PXUP4FMFDU
3*"5FDIOPMPHJFT

%FMJWFSJOH/FYU(FOFSBUJPO
6TFS*OUFSGBDFT6TJOH"+"9

0SBDMF9& "+"9
"TZODISPOPVT9.-JO"DUJPO

'BTU4DBMBCMF
"+"9"QQT

RETAILERS PLEASE DISPLAY


UNTIL SEPTEMBER 30, 2007
Scary Question.
Exactly who is developing your next app?

Contact Us

Address:
555 Not My Home St.
Big City, CO 12345
Your App Starts Here.
We are the leaders in RIA development services.

INCREDIBLE APPLICATIONS

PASSIONATE USERS

PROVEN SUCCESS

Unlock your potential


with the help of industry leaders in
Rich Internet Application development.
10 Years. 1400+ Customers.
Your app starts here.

CYNERGYSYSTEMS.COM
March 2007

n6 Taking AJAX Seriously n22 Oracle XE + AJAX:


From the Editor
Asynchronous XML in Action
by Roger Strukhoff
Building a real application
by Przemek Piotrowski

n8 How to Select and Mark Townsend

RIA Technologies
Choosing between two paths: n28 Quasar’s Nuqleo System
AJAX or Adobe Integrates AJAX into
by Jeffrey S. Hammond Enterprise Publishing
Work flows improve, bottlenecks disappear

n12 Delivering Next-Generation when taking a Web-based approach

User Interfaces Using AJAX


The user experience is absolutely
n30 Fast Scalable AJAX Apps
Finding and eliminating
central to the Web 2.0 model
bottlenecks and bloat
by Rado Kotorov
by Dylan Schiemann

n16 AJAX Done Right


n32 Pushing AJAX into High Gear
Or, how I learned to stop worrying
A simple streaming AJAX example with the
and love the DOM
OpenAjax Hub, TIBCO GI, and DWR 2.0
by John Eckman
by Kevin Hakman and Joe Walker

ajax.sys-con.com May 2007 


From The Editor

Group Publisher Roger Strukhoff

Taking AJAX
Art Director Louis F. Cuffari

Editor

Seriously
Nancy Valentine, 201 802-3044
nancy@sys-con.com

To submit a proposal for an article, go to


http://grids.sys-con.com/proposal.

Roger Strukhoff
Subscriptions
E-mail: subscribe@sys-con.com
U.S. Toll Free: 888 303-5282
International: 201 802-3012
Fax: 201 782-9600
Cover Price U.S. $5.99

I
U.S. $19.99 (12 issues/1 year) t’s fun to watch kids grow up, as is a revolution, a buzzword, or an inflec-
Canada/Mexico: $29.99/year
they move from various cute stages tion point in the history of technology and
International: $39.99/year
Credit Card, U.S. Banks through the obnoxious teen years and civilization. It’s easier to tell what’s hap-
or Money Orders into what passes for maturity these days. pening with AJAX. Separating AJAX from
Back Issues: $12/each On an accelerated timescale, it’s fun to Web 2.0 reveals a seriousness of purpose
watch technologies grow up, too. Some by AJAX proponents and developers, and
Editorial and Advertising Offices
Postmaster: Send all address changes to: mature more quickly than others. Some a future that will be more about improv-
SYS-CON Media mature too quickly and die out, while oth- ing existing infrastructures than trashing
577 Chestnut Ridge Road, ers never seem to mature at all. them.
Woodcliff Lake, NJ 07677
Over the past two years, AJAX as a Improving the customer experience – a
Worldwide Newsstand Distribution general technological approach seems to key goal of AJAX – can be measured by the
Curtis Circulation Company, be maturing very quickly. I won’t bore this very large and very serious companies
New Milford, NJ magazine’s savvy audience by recount- that are now integrating AJAX into their
ing for the umpteenth time how, when, front ends. How quickly can customers
List Rental Information
Kevin Collopy: 845 731-2684,
and by whom the term was coined, and find what they need? How does the new
kevin.collopy@edithroman.com, I fully realize that many of you had been efficiency aid clickthroughs, sales, and
Frank Cipolla: 845 731-3832, working – sometimes for years – with repeat sales? How does it improve the
frank.cipolla@epostdirect.com
JavaScript, XML, and related languages company’s effort to develop and maintain
and approaches before the term AJAX a 360-degree customer view? How does
Promotional Reprints
Megan Mussa came into existence. this compare with competitors? How does
megan@sys-con.com What is important is that AJAX today it compare with potential competitors?
is not the AJAX of early 2005. Seen origi- All of these questions can be answered
Copyright © 2007
nally as part of a communitarian Web objectively and provide information much
by SYS-CON Publications, Inc. All rights
reserved. No part of this publication may 2.0 culture that once again threatened to more concrete than that provided by a
be reproduced or transmitted in any form overturn the so-old, so-dated IT world of mere “wow” factor.
or by any means, electronic or mechani- the past, AJAX is, in fact, now becoming As AJAX becomes less and less about
cal, including photocopy or any informa-
an integral part of any serious enterprise’s “wow” and more and more about develop-
tion storage and retrieval system, without
written permission. approach to its IT infrastructure. ing traditional customer satisfaction, we
Google Maps was seen as the quint- can expect the market for AJAX technology
AJAXWorld Magazine essential AJAX/Web 2.0 manifestation. providers to grow and grow. Enterprises
is published bimonthly (6 times a year)
Raucous start-ups such as YouTube, Digg, are taking AJAX seriously. AJAX is no lon-
by SYS-CON Publications, Inc.,
577 Chestnut Ridge Road,
et al, with huge Web traffic numbers but ger some sort of revolutionary concept;
Woodcliff Lake, NJ 07677. precious few employees were seen as the it is becoming the way to do business.
SYS-CON Media and SYS-CON way of the future. AJAX interfaces prom- It seems as if AJAX has gone from being
Publications, Inc., reserve the right to
ised to enhance the customer experience, the cute kid, skipped those pesky teenage
revise, republish, and authorize its
leave old-fashioned Websites in the dust, years, and become a very nice and pro-
readers to use the articles submitted
for publication. and change the world. ductive young adult.
The trouble with revolutions, though, This may seem like a terribly unglamorous
is that they burn out quickly and don’t statement to all of us who like to act like
always manage to overthrow the existing radicals now and then. But it strikes me as
order. It’s too early to tell whether Web 2.0 a beautiful thing. n

 May 2007 ajax.sys-con.com


Akamai makes AJAX sites perform 5X faster.

As end users graphically edit


price parameters, information
within the main content area
is dynamically updated.

This instance of Google Maps


dynamically updates as
destination cities are chosen.

As arrival and destination times


are modified, flight information
is updated in real-time.

Akamai delivers AJAX Websites up to 5x faster. Ensure To learn more, download a new White Paper:
every transaction is completed with optimal performance Web 2.0 is Here—Is Your Infrastructure Ready?
for each user—even for highly interactive sites. Visit www.akamai.com/AJAX

©2007 Akamai Technologies, Inc. The Akamai logo is a registered trademark


of Akamai Technologies, Inc. All Rights Reserved
Frameworks

How to Select RIA Technologies by Jeffrey S. Hammond

Choosing between two paths: AJAX or Adobe

W
hen it comes to rich Internet appli- have tiny footprints and download to browsers so
cation (RIA) technologies, application quickly that there’s no perceptible lag in app per-
development professionals must choose formance. Some open source AJAX tool kits share
between two paths: AJAX or Adobe. AJAX is the best this trait, but others approach the size of Adobe’s
bet for experienced Web development shops looking Flash and have equally long install times.
to incrementally evolve existing Web applications.
Of course, selecting AJAX also raises the question of Developers and architects may salivate over the
whether to go with a homegrown, open source, or technical merits of AJAX, but managers should note
commercial AJAX framework. that using AJAX frameworks also introduces risk.
In contrast, Adobe is best for shops looking to Unmanaged, these risks can increase costs or derail
completely transform their Web experiences. But a development effort entirely. For example:
to do so, firms must acquire the skills necessary to • It’s easy to choose the wrong AJAX framework.
use Flex, which is the development framework for There are dozens of popular AJAX frameworks,
the Flash runtime environment. Early adopters with and they are not created equal. Developers might
time-to-market concerns and comfort with either want to cut a check based solely on a framework’s
smaller vendors or open source can select AJAX with rich widget set or light-speed performance, but
confidence. But firms that require support from a architects will need to validate that the framework
larger vendor and full-featured development tools supports corporate standards for security, acces-
will do better with Adobe. sibility, service integration, and data access.
App dev professionals should make the selec- • Finding best-of-breed AJAX development tools
tion based on their time-to-market requirements, is difficult. Experienced Web developers don’t
whether they’re looking to evolve or revolutionize mind writing JavaScript and XML in text editors,
their user experience, and whether they prefer tools but most developers in enterprise IT shops pre-
from large established vendors. fer visual designers and WYSIWYG editing tools.
When it comes to AJAX, the only such tool support
AJAX: The Fast Lane to a available at present is tied to commercial AJAX
Better User Experience frameworks, meaning that the choice of one is
App dev organizations that prefer a fast path to necessarily a choice of the other.
RIAs — for developers and users alike — select AJAX • Cross-browser compatibility issues increase test-
for the following reasons: ing costs for AJAX. Testing costs increase in direct
• AJAX helps shops meet time-to-market needs. proportion to the number of browser platforms
Developers with existing Web skills find that and versions to be supported. However, using a
adopting AJAX involves a shift in design patterns, commercial AJAX framework can mitigate these
not a wholesale change in programming language costs, as the framework vendor incurs the cost of
or development tools. cross-browser testing. For example, Software AG
• AJAX favors gradual re-factoring of existing Web certifies its cross-vision Application Composer
apps. AJAX is based on open and standard lan- on multiple versions of browsers like Internet
guages like JavaScript and XML. This makes it easy Explorer, Mozilla, and Netscape.
for developers to integrate AJAX widgets into exist-
ing Web applications that are written in HTML, The AJAX Path Itself Forks with
DHTML, or server-side JavaScript. Homegrown, Open Source, and
Jeffrey Hammond is a senior analyst at • AJAX can deliver speedy performance. Vendors of Commercial Alternatives
Forrester Research where he covers tools commercial AJAX frameworks like Backbase and Just because a development team has chosen
and techniques for application JackBe invest considerable resources tuning their to go with AJAX doesn’t mean that its tool selection
design and development. AJAX frameworks for speed because their clients effort is complete. There remains the important

 May 2007 ajax.sys-con.com


decision of how many and what type of AJAX frame- user’s desktop. Unlike AJAX, Flash doesn’t require
works to use. Today there are three types: browser-specific code or enablement of JavaScript SYS-CON Media
• Many developers create their own frameworks. in the user’s browser. President & CEO
Fuat Kircaali, 201 802-3001
Development teams create their own AJAX wid- • Flex works well for large-scale RIAs. Large-scale
fuat@sys-con.com
gets when they need customized controls that user productivity applications are often designed Group Publisher
work in a specific way. with conversation flows that require access to Roger Strukhoff, 201 802-3040
roger@sys-con.com
• Other developers build on top of open source business data and rules to drive application con-
frameworks. Open source communities engage in text. Flex makes it easy for developers to provide Advertising
a constant process of peer review, which quickly the right business context and flow while keeping Senior Vice President,
separates good design from bad. This leads to response times to a minimum. Sales & Marketing
Carmen Gonzalez, 201 802-3021
successful projects maturing quickly, while poor • Flex is evolving quickly and has a predictable
carmen@sys-con.com
frameworks lose critical mass. When selecting an trajectory. Adobe has invested heavily in Flex, Advertising Sales Director
open source framework, look for active develop- and the result has been sustained improvement Megan Mussa, 201 802-3028
ment communities with committed corporate from release to release. In contrast, the future of megan@sys-con.com
Associate Sales Manager
sponsors, as this is an indication of longevity. AJAX depends on the whims of a dozen vendors
Corinna Melcon, 201 802-3026
OpenLaszlo, Dojo, and the Google Web Toolkit and open source projects that aren’t even loosely corinna@sys-con.com
(GWT), for example, are supported by corpo- federated. In the words of one architect we spoke Events Manager
rate sponsors like Laszlo Systems, IBM, AOL, and with, Flex is “one support framework to rely on, Lauren Orsi, 201 802-3022
lauren@sys-con.com
Google. not dozens to integrate.”
Events Associate
• Commercial frameworks provide a throat to • Flex Builder improves developer productivity Sharmonique Shade, 201 802-3024
choke. Commercial AJAX vendors provide sup- and collaboration with designers. Flex Builder sharmonique@sys-con.com

port and certification of their products, which is provides developers with a visual, WYSIWYG
Production
appealing for managers who are uncomfortable experience on a par with the best commercial
Lead Designer
taking the open source route. They also focus on tools for AJAX. What sets Flex Builder apart from Louis F. Cuffari, 201 802-3035
providing capabilities that enterprise developers these tools, though, are features that improve louis@sys-con.com
Art Director
require, including high-performance clients and collaboration between developers and designers.
Alex Botero, 201 802-3031
tooling that makes it easy for developers to con- Using Flex lets developers and designers at the alex@sys-con.com
nect to enterprise applications. American Cancer Society rapidly iterate through Associate Art Directors
design changes and preview them with stakehold- Tami Beatty, 201 802-3038
tami@sys-con.com
Just as there are myriad AJAX frameworks, there ers within hours.
Abraham Addo, 201 802-3037
are also myriad AJAX framework selection criteria. abraham@sys-con.com
These criteria fall into five buckets: customizability; Flex Developers Are Hard to Find and Other
security and accessibility; widget set; tooling; and Drawbacks of Flex SYS-CON.COM
Vice President Information
cross-browser support. But not all of these criteria But Adobe isn’t perfect. App dev professionals
Bruno Decaudin, 201 802-3051
should be weighted equally (see Figure 1). should consider the following Adobe drawbacks: bruno@sys-con.com
• Flex developers are difficult to locate and com- Consultant, Information Systems
Adobe’s Solution Is Powerful, Predictable, mand a premium rate. Flex developers are harder Robert Diamond

and Productive to find and more expensive to retain than AJAX


robert@sys-con.com
Web Designers
Adobe is an attractive RIA solution because it developers: In the United States, they start at Stephen Kilmurray, 201 802-3053
combines powerful development tools (Flex) with $60,000 and top out around $120,000. One execu- stephen@sys-con.com

a near-universal browser plug-in (Flash) that’s tive at a North American financial services firm we Richard Walter, 201 802-3057
richard@sys-con.com
designed to simplify RIA deployment. Managers who spoke with had to retain talent from South Africa
have concerns about small commercial AJAX provid- and the Czech Republic to deliver a successful Accounting
ers or support issues with open source AJAX frame- project. As more developers ramp up on Flex this Financial Analyst
Joan LaRose, 201 802-3081
works consider Flex a safe alternative. But there is a issue will subside, but for now it makes Flex more
joan@sys-con.com
downside: To be productive in Flex, developers have expensive in the short-term than Ajax. Accounts Payable
to learn two new languages and an extensive run- • Flash upgrade issues can defeat the deployment Betty White, 201 802-3002
time framework — something that can take between value proposition. When users aren’t on the lat- betty@sys-con.com

one and three months to learn. Once this initial est version of Flash, requiring them to upgrade is
Customer Relations
hurdle is cleared, Adobe adopters see the following risky because almost half will abandon the site. Circulation Service Coordinators
benefits: Many are unwilling to wait through the lengthy Edna Earle Russell
• Widespread adoption of Flash speeds deploy- install process and instead choose to do business edna@sys-con.com
Alicia Nolan, 201 802-3081
ment. When Flash is already installed, application elsewhere — potentially with the competition.
Alicia@sys-con.com
deployment requires no additional changes to the • Success can create an unexpected user response.

ajax.sys-con.com May 2007 


Flash is a broad graphical canvas, and Flex allows releases. Finally, AJAX’s customization capabilities
designers to push the boundaries of rich media make it possible to tune client frameworks to meet
further than AJAX does. This can lead to a situa- specific application footprints; this makes AJAX the
tion where users become distracted by a mix of better solution for smaller RIA deployments and for
Flash’s rich media and Flex’s new controls. IT orga- deployments where performance is critical.
nizations can avoid this response by introducing For large-scale user productivity applications,
rich media gradually and frequently conducting developers should use Flex. Although Flash’s client
A/B testing with focus groups. footprint is larger than AJAX frameworks, its mar-
ket penetration makes it the preferred deployment
Which RIA Technology Is Best for You? platform for larger, comprehensive RIAs. Adobe is a
When aggressive developers push the boundaries safe choice for those who put a high value on reliable
of RIA development, they quickly run into barriers support and product continuity, concerns that are
that affect their ability to take full advantage of RIA key when making strategic technology investments.
technology. Firms interviewed recently by Forrester The downside is that safety comes at the price of
Research cited several barriers to their RIA develop- openness.
ment efforts that no tooling available today could The benefits are clear: RIAs help users find and
overcome (see Figure 2). manipulate relevant content, complete complex
In selecting an RIA technology, application transactions, and consume multimedia in the con-
development professionals should choose AJAX text of a larger app, providing improved customer
when time-to-market is critical and updates are experience, higher Web conversion rates, and thus
frequent. Experienced Web developers ramp up on improved revenues. While there’s no one answer to
AJAX quickly. AJAX also makes it easy to build RIA the question of which to use, AJAX and Flex provide
capabilities into existing apps with small, frequent today’s developers with options. n

Figure 1:

Figure 2:

10 May 2007 ajax.sys-con.com


“Pre-built Ajax widgets, cross-browser
compatibility and the full support of the
Backbase team were the keys to our
selecting Backbase.”
Robert Leerdam, Project Manager, ABN/AMRO

Backbase Enterprise Ajax: The Complete Development Solution for Ajax

TRY IT
NOW!

Download a free trial at


www.backbase.com

Product Highlights
• Cross-browser Ajax client runtime • Server-side integration with Struts and JSF
• Simple and easy-to-use Ajax tags • Section 508 / WAI compliance
• 100+ Ajax widgets w/ source • Extensive documentation and tutorials
• Ajax development tools • Sample applications
• Debugging and testing tools • Open API
• SOA integration • Proven RIA blueprint implementations
• Integration with portal servers • Comprehensive 24x7 support

For more information, call 866-800-8996 (Americas); +31 20 465 8888 (ROW)
Web 2.0

Delivering Next-Generation by Rado Kotorov

User Interfaces Using AJAX


The user experience is absolutely central to the Web 2.0 model

B
y any reckoning, the Internet and the World mail. Web 2.0 and AJAX-based applications represent
Wide Web have remade the way we do busi- an opportunity to fully realize the Web’s potential to
ness. The ascendance of the Web-based make users smarter and more productive, and that
enterprise has come to be seen as inevitable. But opportunity extends to the most sophisticated back-
anyone who takes a hard look at the serious limita- end and analytic applications.
tions of first-generation Web applications is likely
to have a renewed sense of wonder at the spread How We Got Here: Evolutionary Steps to
of their adoption thus far. Users experimented with Web 2.0
e-mail, instant messaging, and search engines and As any significant technology evolves toward
turned them into real communication, collabora- maturity, attention shifts from the technology itself
tion, and information-gathering tools. Those same to the work that the technology enables. That shift is
business users endured their fitful interactions with clearly manifest in Web 2.0, the third major phase of
static HTML pages and moved applications to the the Web’s evolution, which can be summarized like
Web anyway because of the substantial savings this:
promised by the shift. • Web 1.0 – Content delivery and communication.
Now their patience is about to be rewarded. This early stage changed the dissemination of
Emerging from a decade of groundwork is Web 2.0, information via two innovations, HTML pages and
which offers dramatic gains in productivity for indi- e-mail.
vidual workers and whole enterprises. Web 2.0 appli- • Web 1.5 – Content personalization and multi-
cations are distributed collaborative tools available level communication. Search and personalization
on-demand from any browser anywhere. And those made the spread of information more efficient,
tools are constructed to be at least as intuitive and while chat rooms and instant messaging expand-
easy-to-use as any application loaded on a desktop. ed communication in real-time.
Web 2.0 is based on many technologies – most • Web 2.0 – Authoring and collaboration. This cur-
prominent among them being Web Services, rent stage is not about the dissemination of infor-
Asynchronous JavaScript and XML (AJAX), mation, it’s about productivity – accomplishing
Cascading Style Sheets (CSS), and Really Simple work-related tasks in a virtual space with tools and
(Web) Syndication (RSS) – and the list will continue applications that are available anywhere, at any
to grow. Of these, AJAX has attracted the most atten- time, and can be shared collaboratively.
tion recently because it’s the technology that most
effectively fills the gap between the user experience In the past, Web applications’ lack of respon-
of Web and desktop applications. siveness and dearth of controls offset most of their
And the user experience is absolutely central advantages as thin-client tools. In contrast, desk-
to the Web 2.0 model. Web 2.0 applications must top developers have historically taken advantage of
possess a set of user interface components that two capabilities of Windows that make applications
are as compelling and responsive as a desktop- more intuitive and user-friendly than their Web
based environment. Developers can no longer be counterparts: richness and responsiveness. When a
satisfied to offer discontinuity in user experience, complex and robust set of UI components is com-
Rado Kotorov is a technical director of stra- because widely distributed, frequently mobile users bined as they have been on the desktop, they make
tegic product management for Information won’t be able to tolerate it and do their jobs well. the user interface natural, informative, and intui-
Builders, Inc., responsible for emerging The improved user experience will include, but tive to use. And when the application and the user
reporting, analytic, and visualization must extend beyond, the most common productivity interface quickly adapt to user actions, they create
technologies. tools, such as word processing applications and e- an uninterrupted interaction. Windows applications

12 May 2007 ajax.sys-con.com


don’t stop to reload, forcing users to move through never leaves the application – never loses context
tasks in stops and starts – or causing them to lose the or suffers interrupted workflow – because no action
thread of the business process entirely. triggers the reloading of a full page.
The user experience gap between Windows and This seemingly small change has a profound
the Web has been due to the limitations of the early effect on the user’s experience. Transferring more of
Web client/server model, with the Web server as the the interaction to the client side not only improves
platform for all processing logic and the browser as the the workflow, it also allows the addition of enrich-
client handling nothing more than the data display. In ing UI components, which put AJAX-based Web
this architecture, users interact with HTML and each applications on a par with desktop applications for
of their actions triggers a request to the server, which usability. There are, it should be noted, alternatives
in turn triggers the generation of a new page. to AJAX – Adobe’s Flash technology also provides a
The incessant reloading of the page severely means to develop rich clients and DHTML allows
limits the user experience for a couple reasons. First, one to partially upload components on an HTML
flipping from page to page can disorient the user as page without reloading the entire page. But AJAX’s
the allocation of tasks on different page views causes combination of cross-browser compatibility, zero
loss of context. On top of that, reloading the page footprint, and ability to provide interactive com-
causes a disjointed and rigid interactive flow. The plexity to the user gives it a leg up on the competi-
user has to wait for the next page to initiate a new tive technologies.
interaction or change the workflow, or be bounced The improved interactivity of Web 2.0 applications
back to the previous page to alter information in is driving even more applications off the desktop,
a field. Think of the online shopper on a retail site since the lower total cost of ownership now comes
who can’t order three shirts instead of two without without the offsetting negatives of cumbersome
returning to page one, and then extend the problem user experience. These transitional Web 2.0 applica-
to business users struggling with enterprise applica- tions enabled by AJAX have been productivity tools,
tions throughout their workday. such as word processing and e-mail applications,
The difficulties of the interaction are compound- calendars and spreadsheets. Examples are Google’s
ed as the complexity of applications and user options recently released Writely and Google Spreadsheets;
increases. For example, imagine the user experience competitive word processors like Zoho Writer, Abe
of writing a document in an application created in Writeboard, and ajaxWrite; Num Sum spreadsheet
Web client/server mode. For each paragraph, the functionality; and 30 boxes, a Web-based calendar.
user must open a dialog, enter the text in the input Web-based desktops are also emerging, like the one
box, and wait for the changes to be applied to the available at www.desktoptwo.com.
document when the page is refreshed. And then all Their lower TCO comes from centralizing most of
the steps must be repeated for every edit or format the software in a single location on the server, with
change. The frustrated user needs plenty of patience only a browser installed on desktops throughout the
and training to work with the tool. organization. This lowers installation and mainte-
nance costs, provides for incremental upgrades to
Enter AJAX existing applications, creates user administration
By contrast, AJAX combines technologies such savings, and offers enterprise-wide control over doc-
as asynchronous JavaScript, the Document Object ument backup and archiving, as well as compliance
Model, XMLhttpRequest, XHTML, and CSS so the and security. The Web 2.0 model makes applications
user can incrementally update any element of an
application that resides in the browser. The user – continued on page 18

ajax.sys-con.com May 2007 13


Solutions

AJAX Done Right by John Eckman

Or, how I learned to stop worrying and love the DOM

T
he Bad Old Days, or, I Walked a Hundred Miles Some JavaScript developers learned to create
to School, in the Snow, and It Was Uphill Both applications with a series of if-then statements
Ways pointing to specific versions for specific browsers,
Back in the late ’90s, people started to use the replicating the functionality in each major “support-
term “Dynamic HTML,” often shortened to DHTML, ed” browser. Sometimes this led to unanticipated
to describe the use of JavaScript to manipulate results, as when the tests were too specific (look-
HTML in the browser. Basic DHTML meant rollover ing for a particular version of a particular browser)
images that changed state when you moused over they often broke when new browsers were released.
them or drop-down menus that cascaded down (Smarter developers learned to test for specific func-
from the top navigation. More complex DHTML tionality, rather than looking for a particular browser
concepts included dragging-and-dropping objects, version – but this could still lead to a number of code
hiding and revealing content, and even whole games branches for different browser levels.)
built purely from HTML, images, and JavaScript. Some Web designers found an alternative in
The problem with DHTML, of course, was that it Flash. Flash enabled designers to create animation,
was tremendously hard to do. More accurately, it was use sound, and create interactivity on the page
tremendously hard to do well in a cost-effective way. without having to worry about browser versions and
It was certainly possible to do some of the simpler platforms. Because Macromedia (now Adobe) is the
functions (drop-down menus, mouseovers) in a reli- sole supplier of the Flash plug-in, it can offer com-
able cross-browser, cross-platform way. But anything plete control over the experience for both developers
more complicated than that quickly ran into the and users. Designers who resisted the urge to create
problem of alternate browser implementations: for monster intro movies and used Flash judiciously as
example, using the “layer” tag for Netscape 4, but the a supplement to an HTML page, rather than as a
“iframe” for Internet Explorer and newer Netscape/ replacement for it, found great power in the ability
Mozilla browsers. Similarly, Internet Explorer 5.x and to add interactive elements and animation without
John Eckman leads the Next Generation later supported document.getElementByID() as did having to decipher the complexities of DHTML.
Internet Practice at Optaros (www.optaros. the Mozilla-based browsers, but Internet Explorer (A number of these first-generation Web designers
com), and has over a decade of experience 4.x relied on document.all, and Netscape 4.x on abused Flash’s power, creating unnecessary ani-
designing and building Web applications document.layers. mation, breaking the very interface conventions
for organizations ranging from small The whole experience got confusing rather quick- new Web users so desperately needed, and sticking
non-profit organizations to Fortune 500 ly, leading to a number of different alternatives. “introduction” movies in front of Web pages, leading
enterprises. John´s technical background Many individuals coded applications or sites to the birth of the infamous “Skip Intro” button. See
includes J2EE and .NET frameworks as well directly to a single browser, leading to the phenome- http://www.skipintro.nl/skipintro/ for a humorous
as scripting languages and presentation- non of “Best Viewed in…” badges on sites. (I thought version of the problem.)
tier development approaches, in addition this behavior had gone the way of the “blink” tag, Finally, a significant number of information
to information architecture, usability test- but Wal-Mart’s recent digital download site exhibited architects and Web designers simply learned to avoid
ing, and project management. He received similar behavior – for several weeks following the DHTML altogether, or at least to avoid any of the
a BA from Boston University and a PhD launch, the site greeted Firefox visitors with an apol- “more complicated” functions. I remember seeing
from the University of Washington at ogy: “We’re sorry. Our Web site requires the browser statements of work for Web development that either
Seattle; he expects to complete an MS in Internet Explorer version 6 or higher. It appears that specifically excluded anything but the most basic
Information Systems from Northeastern you’re using Firefox, Safari, or another browser that DHTML or noted that DHTML use would increase
University in 2006. He also achieved PMP Wal-Mart Video Downloads doesn’t currently sup- risk and cost. If you didn’t have the right JavaScript-
certification in 2003. port.” In early March, however, it appeared that the and browser-savvy resources as part of your Web
jeckman@optaros.com problems had been rectified.) team, it was undoubtedly safer simply to stay away.

14 May 2007 ajax.sys-con.com


None of these approaches, of course, solved ing away the plumbing to handle multiple browser
the core problem, or provided a repeatable, cost- implementations and interpretations.
effective (in terms of development and debug- We have to be wary, however, of the assump-
ging time), standards-based, plug-in independent, tion that just because developing AJAX-style Web
cross-browser solution to browser-side interactiv- applications has gotten easier, we’ve gotten better at
ity. developing them.
Just as word processing software doesn’t (in and
There’s Got to Be a Better Way: AJAX of itself ) improve one’s writing, having access to
The solution, as readers of this publication frameworks that facilitate AJAX-style development
undoubtedly recognize, came in the form of AJAX. has increased the potential for users to develop truly
As I’ve written in an earlier article in these pages, both good usable applications and horrible unus-
Jesse James Garrett’s essay became such a perva- able applications.
sive meme precisely because it appeared to cut the How can we avoid the “Skip Intro” phase of AJAX
Gordian knot that had long plagued Web develop- development and move right into the mature, stable,
ment using JavaScript. What Garrett’s “AJAX” did was usable application era?
to give a name to a series of approaches that had
been many years in the works: First, Do No Harm: Don’t
Break the Back Button
As the user base of the old Netscape 4.x applica- It’s crucial that while AJAX can make Web applications
tions waned, and the availability of new platforms more like desktop applications, it should not remove the
rose, developers were emboldened by the relative ease strengths of Web applications in the process or interfere
of developing cross-browser standard applications in the fundamental architectures of the Web.
with rich interaction in JavaScript and CSS, more and This means, first and foremost, not breaking the
more developers started to create AJAX applications. conventions of back button use, bookmarking, and
Garrett’s essay crystallized this movement and gave it link sharing. Granted, these conventions may have
a name. different meaning in different applications, but they
While Garrett referred directly to the use of should be thoughtfully considered and only dis-
Asynchronous JavaScript and XML, the name rupted for a specific rationale. Full AJAX applications
is commonly applied to all kinds of uses of that provide rich interactive functionality but aren’t
JavaScript for interactivity: some entirely syn- conceptually linked to a page-based interface may
chronous, and many bypassing XML in favor of not be able to support the conventional use of the
data representations like JSON. The point really back button. If the interface has no notion of pages,
is that the AJAX label effectively negated the and is all in a single HTML page, what sense does the
fears associated with DHTML, and signaled to back button make?
the development and design communities (as For example, Zimbra’s Collaboration Suite, a
well as the customers who write the checks for Microsoft Outlook- or Lotus Notes-style e-mail client
site development) that it was now possible to and calendaring system, doesn’t “support” the back
build client-side interactivity without immense button in the sense of allowing the user to click on
pain. the browser’s “back” button and somehow change
Buoyed by the excitement over the Mozilla proj- the interface to the last viewed page or last entry in
ect, and the relative stability of the Document Object the browser history. Because the entire application
Model (DOM), a number of frameworks emerged lives in a single page at a given URL, allowing the
to make AJAX-style development easier, abstract- “normal” function of the back button would result

ajax.sys-con.com May 2007 15


in jumping back out of the application. understood in new ways.
However, Zimbra doesn’t simply disable or hide First, never trust any data that comes from the
the back button. Instead, the application pops up a client. This has been a truism of Web development
confirmation dialogue (the same dialogue is used for from the beginning. In fact, this was true in cli-
other browser-actions that would navigate away, like ent/server environments as well: just because it was
clicking on a bookmark, or typing a new address in much more difficult in client/server environments
the address bar) as shown in Figure 1. for someone to manipulate the client didn’t mean
This elegant solution lets the user remain in that client input shouldn’t be checked.
control rather than deciding on the user’s behalf. The difference that an AJAX application intro-
If, indeed, the user intended to navigate away from duces, as compared to a traditional Web applica-
Zimbra – perhaps using the application for now – the tion, is the fact that more data manipulation and
user can simply hit OK and be off to the requested processing can be done on the client, and more
page. If the user didn’t intend to navigate away, a complex interactions can be expected between the
simple cancel returns them to the active context client and server. The developer has to be aware
without interruption. that the threshold is fairly low for users to create
Google’s Gmail, on the other hand, supports the alternate clients that return falsified, inaccurate,
back button by taking meaningful action when the or (worse) deliberately malicious data. Any kind of
user clicks it. If you’re viewing your inbox and click Web input form was always already subject to such
on a particular message, Gmail loads that message forgeries and attacks – but in an AJAX Web applica-
in the center content pane. Click on the back button tion you may have many more of them.
and you return to the inbox view. Because Gmail While one might be tempted to assume that an
treats the different views in a fashion consistent with HTTP request generated by a client-side JavaScript
the Web-native page metaphor, it makes sense that function deep within your complicated application
the back button should funct ion this way. is less likely to be forged than a simple Web form, but
Similarly, applications that run in Web brows- this is a slippery slope. Far better to assume that any
ers should either support or provide meaningful input that comes from the client (either directly from
alternatives to bookmarkability and link sharing. the end user or from a JavaScript function) is guilty
Google Maps is a wonderful example of this, pro- until proven otherwise.
viding a “link to this map” icon that enables users Second, don’t send data to the client that you
to reproduce a complex map, complete with zoom don’t want the user to see. This has also been a Web
level, map type, and current center point, simply by truism from very early on. Many systems are careful
providing a URL. in responding to failed logins to avoid giving more
information than necessary about what went wrong
Learning What Not to Do, All Over Again: – typically not telling you, for example, whether
Security in AJAX Applications there is or isn’t a username matching what you
Some have argued that AJAX applications are nec- entered, just that the username-password combina-
essarily more insecure than traditional Web applica- tion is invalid.
tions, because they inherently expose a larger “attack The fact that AJAX offers the ability to do client-
surface.” While I’m not certain I agree with calling side form validation doesn’t mean that you can skip
any broadly defined development approach inher- server-side validation (remember truism number one
ently less secure – we’ve all seen how poor develop- above), and it also doesn’t mean that you always
ment practices can make any application prone to should do client-side validation. Doing so will reveal
successful exploits – these critics are right to point to to the user what the correct formats are. (In general
two specific concerns. These concerns are not in fact this is not a bad thing – but if, as in one recent public
unique to AJAX development, but they do have to be example, what you are validating is a “discount code,”
revealing that code to prying eyes is a no-no).

The Internet Is a Series of Tubes, and the


Tubes Can Be Filled: Keeping Traffic Light
Another common complaint about Web applica-
tions that leverage AJAX is that they can be hard on
the infrastructure: creating additional traffic through
a higher number of requests and swelling bandwidth
as large JavaScript files are downloaded. Although
the increasing prevalence of broadband has made
Figure 1: Confirmation Dialog
site download size less of a factor, it’s still critical

16 May 2007 ajax.sys-con.com


Advertising Index increase the number of requests each client makes.
Advertiser URL Phone Page The perceived performance is much more difficult
Akamai www.akamai.com/AJAX 7 to measure, but has to do with how responsive users
BackBase www.backbase.com 866-800-8996 11 perceive the application to be. If certain requests are
Cynergy Systems www.cynergysystems.com 2-3
made asynchronously, they may appear more respon-
ICEsoft www.icesoft.com 877-263-3822 17
JackBe www.jackbe.com 240-744-7620 19 sive when the user actually examines the data, having
Laszlo www.laszlosystems.com/go/webtop 4 been “pre-fetched.” On the other hand, if the number
NexaWeb www.nexaweb.com 27 of asynchronous calls going on is high, it may actually
Passport www.passportcorp.com 800-926-6736 35
begin to negatively impact the users’ experience.
SoftwareAG www.softwareag.com/Ajax 29
Telerik www.telerik.com/prometheus 36 The key is that at the end of the day, actual per-
TIBCO http://developer.tibco.com/ 23 formance and perceived performance are tenuously
Advertiser index is provided as an additional service to our readers. Publisher does not assume any liability
linked: applications with lower actual performance
for ommissions and/or misprints in this listing since this listing is not part of any insertion order.
may be perceived as having higher performance, and
vice versa, depending on the end users’ experience.
that Web-based applications don’t ignore bandwidth (Of course, there are infrastructure cost factors to the
consumption and traffic generation. actual performance as well, perceptions aside.)
AJAX developers should pay close attention Your best bet is to prototype rapidly, measure early,
to caching strategies, designing, segmenting, and and improve iteratively. Don’t wait until the end of a
combining code so that libraries of JavaScript can cycle to discover that your application will saturate
be aggressively cached on the client and don’t your connection or take prohibitively long to load.
require frequent downloads. In addition, develop-
ers shouldn’t overlook compression options for The More Things Change…
JavaScript code. All in all, the good news is that the principles that
It’s also important to be cautious about the net- make well-designed AJAX applications aren’t radi-
work travel your AJAX application generates. cally different than those that have been best prac-
Remember that there are two important factors at tices all along in Web-based applications. The new
play: actual performance and perceived performance. capabilities AJAX offers inevitably create scenarios
The actual performance is the volume of requests where there is no clear design consensus and where
the Web server handles in a given unit of time, and it the application of the principles requires careful
includes asynchronous JavaScript calls as well as the planning, thoughtful design, and a fair amount of
direct user-initiated clickstream. AJAX applications trial and error.
often increase the number of HTTP connections each But it sure beats DHTML and the “Stupid Browser
client will make to the server, and may or may not Tricks” it forced on us. n

– continued from page 13 which is, after all, the goal of business intelligence.
Organizations were moving applications to the
instantly available to users, eliminating desktop Web even before the emergence of Web 2.0 and
installations. And it’s a model that can be extended AJAX-based tools because cost savings were so
to applications across the enterprise. attractive that they trumped the limitations of first-
For example, as sophisticated analytics and busi- generation Web applications. Now, with Web 2.0
ness intelligence information are pushed further out applications that provide a user experience equal to
into the enterprise, it is essential that applications that of desktop applications, that trend is going to
deliver the information smoothly, clearly, and in an build momentum rapidly.
uninterrupted context. AJAX provides the foundation For several years, enthusiasts have predicted that
for user interfaces based on reusable components, the impact of the Internet and the Web will rival that
each of which enables a set of UI functions that can be of the Industrial Revolution. Driven by the same
manipulated individually for or by the user. The flex- need to use resources more effectively and increase
ibility inherent in AJAX-enabled applications translates productivity as that earlier transformation, Web 2.0
into quick, easy rollouts of new functionality as user could make those predictions come true. But instead
needs change, as well as the ability to customize the of centralizing workers and machines in factories,
interface for users based on their roles and specific Web 2.0 will liberate a distributed, mobile workforce
needs. Improving the user experience translates into by offering consistent access to applications and
a parallel improvement in the user’s ability to apply information anywhere in the complex world of the
high-level information to the decision-making process, global enterprise. n

18 May 2007 ajax.sys-con.com


Facing a few barriers
on the road to SOA?

JackBe’s Rich Enterprise Application (REA) platform


clears the road to SOA business benefits.
There’s an abundance of products and vendors to help you create your SOA. Now, consume
those SOA services with JackBe REAs to achieve the business productivity and results that led
you to SOA in the first place. Our new REA platform combines the power of Ajax and SOA with
reliable, secure communications to extend your SOA directly into powerful business applications.
A fully visual IDE reduces manual coding and accelerates the development process. And our
lightweight, vendor-neutral platform easily integrates with existing middleware and services while
maintaining server-side governance and control--unlike products that leave governance to the
browser or create middleware platform dependencies.
Join over 35 industry leaders like Citigroup, the U.S. Defense Intelligence Agency, Sears,
Tupperware, and Forbes who are already optimizing their business activity with JackBe solutions.
Call or visit our website—let us help you remove the barriers on the road to achieving real
business value from your SOA investment.

Web: www.jackbe.com
Phone: (240) 744-7620
Optimizing Business Activity Email: info@jackbe.com
Inside Look

Oracle XE + AJAX: by Przemek Piotrowski


and Mark Townsend

Asynchronous XML in Action


Building a real application

T
his article covers the process of building a real lation so you need to unlock it first using the SYSTEM
working AJAX application on top of Oracle’s account through SQL*Plus (this command will also
free database software. The demonstration set a new password for HR):
takes advantage of features integrated directly into
Oracle Database 10g Express Edition (Oracle XE), the SQL> alter user hr identified by hr account unlock;

Embedded PL/SQL Gateway and Oracle XML DB,


which let you serve XML content derived from SQL User altered.

queries directly over HTTP protocol.


You’ve probably run up against one of the On Windows, accessing Oracle XE’s storage area is
numerous frameworks for AJAX that were proba- trivial with the Web Folder Access feature of Microsoft
bly Java- or .NET-based. Although they fit large- Internet Explorer; just select File > Open and type
scale environments perfectly, smaller projects may http://localhost:8080 in the address field and the
not require such overwhelming resources as a J2EE Open as Web Folder checkbox. Then you’ll be prompt-
stack. Besides, understanding the technology behind ed for a login and password. Supply hr twice here.
XMLHttpRequest may help you use asynchronous If working under Linux or Windows you may
requests better under just about any Web develop- choose to leverage the FTP server built into the XDB
ment environment. component of Oracle Database 10g. You activate it by
The concept is surprisingly simple – to make Web connecting via SQL*Plus as SYSTEM and issuing the
applications more responsive so that they behave like following commands:
regular desktop software. Waiting for a page to reload
Przemek Piotrowski has been following just to see a change in a single place seems like a com- Connected to:

Oracle 10g Express Edition (Oracle XE) plete waste of both time and bandwidth. Having said Oracle Database 10g Express Edition Release

development since its early beta stages back that, using AJAX to create Web applications is good not 10.2.0.1.0 - Production

in 2005 and can easily distinguish the new only for the end user, but for the Web server as well.
features in this first database from Oracle Applying this relatively simple technique boosts SQL> exec dbms_xdb.setftpport(‘21’);

that’s free to develop, deploy, and distribute. your Web applications’ usability many times. The
Oracle XE’s small footprint doesn’t stop potential of AJAX is so big that Web applications now PL/SQL procedure successfully completed.

him from taking advantage of many of its have a real chance of replacing desktop programs
advanced features and plugging them into without degrading the user experience. SQL> alter system register;

existing Web architectures.

Prerequisites System altered.

Mark Townsend is vice-president of data- All you need is access to an Oracle XE database
base product management in Oracle’s instance and its WebDAV folders. Oracle XE is much The first command enables the FTP listener in the
Server Technology Division. His responsibil- more than just a database server: Embedded PL/SQL database, while the latter registers the just-activated
ities include requirement analysis, release Gateway makes it a regular Web server, while the listener on PMON (process monitor) without actually
planning, coordinating database product built-in WebDAV and FTP listeners let you connect waiting for its 60-second refresh cycle. Now you can
management activities, communicating and store files served over HTTP directly through connect to the server with any FTP client or directly
with analysts and the press on database one of these protocols. This tutorial assumes that you from the command line (ftp localhost).
topics, and the development and delivery have Oracle XE installed on your local computer. So Now we can upload static files into the database storage
of field technical training. He was product that URLs refer to localhost, you may have to adjust it area. What about dynamic content? The Embedded PL/
boss for Oracle XE. Mark has been with to fit your network’s configuration. SQL Gateway – introduced for the first time within Oracle
Oracle since 1991 and has specialized in I’ll be using the sample HR schema that ships with XE – enables you to access stored procedures directly
the Oracle database for over 15 years. Oracle XE. By default it remains unlocked after instal- from a Web location. Using the http://SERVER_ADDRESS:

20 May 2007 ajax.sys-con.com


PORT/apex/SCHEMA_NAME.PROCEDURE_NAME syn- Outputting XML from SQL Queries
tax one can use PL/SQL stored procedures to trigger data- You can generate XML directly from SQL queries
base events and generate content. For security reasons using the PL/SQL package DBMS_XMLGEN, which
this feature has been disabled by default in Oracle XE doesn’t depend on Java and so is available on XE. The
so you have to unlock it first. Since this is a component query process takes four basic steps:
of Application Express you have to modify the WWV_ 1. Get the context by supplying a valid SQL query.
FLOW_EPG_INCLUDE_MOD_LOCAL function inside the 2. Set options on the newly created context using the
FLOWS_020100 schema. As shown in Listing 1, you have DBMS_XMLGEN procedures (optional).
to make two changes: comment out the return false state- 3. Get the XML result by using getXML() to get CLOB
ment just after begin and add the name of a stored proce- or getXMLType() to obtain XMLType. At this point
dure you’d like to grant external access to (in this tutorial you can also limit the number of rows returned by
we’ll be running HR.AJAXE stored procedure listed later). the XML engine using the setMaxRows() proce-
(Listing 1-6 can be downloaded from the online version of dure on the context.
this article at http://webddj.sys-con.com) 4. Reset the query to perform step 3 again or run
This strict policy on running stored procedures closeContext() to free up allocated resources.
prevents one from executing arbitrary PL/SQL code
on the server side, which would be a major security Unfortunately DBMS_XMLGEN has one flaw that
risk. Using allowed procedure names makes it con- you’ll run up against almost immediately when working
venient to limit execution. To finalize this step, grant with remote XML – HTP.PRN, which will be used to print
execute privileges on the AJAXE procedure to PUBLIC the output accepts strings of a VARCHAR2 type that can
(in SQL*Plus while logged in as SYSTEM or HR): be 4,000 bytes long. This isn’t much for XML to deal with.
The AJAX_XMLHTP procedure was created, which takes a
SQL> grant execute on hr.ajaxe to public; context as a parameter and using the DBMS_LOB PL/SQL
package outputs XML in 4,000-char chunks, leveraging the
Grant succeeded. possibilities standing behind LOBs. (see Listing 2).

Figure 1: AJAX application concept

ajax.sys-con.com May 2007 21


This procedure will handle all the processing work
for us by setting the content type to text/xml (required
by the XmlHttpRequest object for DOM process-
ing), setting null handling to output empty tags for
null values, and disabling pretty printing for smaller
response size. Also, when something goes wrong at
the query level, e.g., empty result set or invalid query,
the procedure manually outputs the hard-coded “No
data found” message to indicate its state.
The AJAXE procedure will be a core dispatcher of
responses. It will accept two parameters: q – the type
of action requested, w – the extra parameter required
for certain types of action (optional) (See Listing 3).
The functionality of the sample application will be
divided into three basic use cases:
• Filling the SELECT list with elements obtained
through the AJAX request and hooking the event
handler to it
• Obtaining the results set and rendering it into a
HTML table dynamically
• Using simple auto-complete on the HTML input
field
Note that both these procedures have to be created
in the HR schema to work. At this point you can test
whether the procedure is working for you by access-
ing http://localhost:8080/apex/hr.ajaxe?q=count
(remember to adjust the URL to reflect your system’s
configuration). A valid XML document should be out-
putted at this address. You’re halfway through.

Hands-on Document Object Model (DOM)


AJAX extensively relies on a set of JavaScript pro-
gramming techniques once referred to as DHTML.
But now they’re much more powerful thanks to the
unification of the DOM implementation among
Web browser vendors. Back in the days of Netscape
Navigator 4 and Microsoft Internet Explorer 4 you had
to use a different syntax for each browser to manipu-
late page content dynamically. No need to do that
anymore.
The Document Object Model is a tree-like hierarchi-
cal representation of nodes/HTML elements (see Table
1). The root node of an HTML document is the <html>
tag that usually has two children: <head> and <body>
– the manipulations happen in the second. Since DOM
is a vast subject, we’ll focus only on the most useful
properties and methods of JavaScript XML objects. For
the complete DOM specification, see the W3C Web site at
http://w3.org.
Again, remember that there are a number of other
JavaScript methods for working with the DOM object.
For purposes of this article, an ajaxTable function
was created: it builds up the HTML table from the
XML response obtained through the AJAX request.
By default DBMS_XMLGEN returns a XML tree of the
following structure:
Table 1: JavaScript Document Object Model

22 May 2007 ajax.sys-con.com


<?xml version=”1.0”?>

<ROWSET>

<ROW>

<COLUMN1></COLUMN1>

<COLUMN2></COLUMN2>

...

</ROW>

...

</ROWSET>

The code in Listing 4 represents the body of the


ajaxTable function.
This function appends the DOM tree in Listing 5
to the DIV element of ID=”q” (the TBODY element
is required here to render properly under Internet
Explorer).

AJAX = Asynchronous JavaScript and XML


Technologically, AJAX is nothing new. It owes its recent
popularity to the unification of the JavaScript standards
that allow access to the XmlHttpRequest object. XML isn’t
new either. It now plays a key role in data and informa-
tion interchange and is universally adopted by both the
enterprise and the open source community. The biggest
problem with the Web was that applications needed a
full-page refresh after each user action on the page. It
didn’t matter whether it was just sorting table elements or
downloading a whole new page.
There are a number of AJAX frameworks on the
market, including the Dojo Toolkit, Prototype, or
Microsoft Atlas to name a few. However, writing basic
handlers alone helps enable a deeper understanding of
what’s happening under AJAX’s hood. First, we need an
XmlHttpRequest object that unfortunately still depends
on the browser – Microsoft Internet Explorer continues
handling it using an ActiveX control so the appropriate
requests object creation code is presented in Listing 6.
This is the only part that requires browser-compatibility
code. Everything else here is cross-browser.
As for the handler, a dedicated function to handle
all the asynchronous operations was created. It takes
a request method, a URL, and callback functions
as parameters. After the response is obtained the
callback is immediately called with the fetched XML
passed as an argument.

function async(method, url, callback) {

request.open(method, url, true);

request.onreadystatechange = function() {

if (request.readyState == 4 && request.status ==


Table 2: XmlHttpRequest object methods and properties
200) {

24 May 2007 ajax.sys-con.com


callback(request.responseXML); FTP or WebDAV, which contains the complete code
} for the sample application. After putting it into the
} /public/ folder of XE, open http://localhost:8080/
request.send(null); public/hr-ajax-demo.html with your Web browser.
} After carefully following all the steps of this tutorial
the demo page should pre-load the list of depart-
The callback function will do all the DOM process- ments and respond to user interaction almost imme-
ing based on the XML content from the response. diately.
The callback works directly on the XMLDocument
JavaScript object. Advantages and Potential Problems
Although programming AJAX isn’t necessarily dif-
Putting It All Together ficult, the question is whether asynchronous query-
Now that we have all the building blocks of ing techniques are safe and production-ready. AJAX
the solution, let’s take a look at the logic behind isn’t always a sure choice over standard development
it. Figure 1 separates client side and server side methodologies. There are at least several viewpoints
into three separate blocks: Oracle XE, Web page, to consider.
and browser client. Notice that the Web page has
been separated here because of its state-depen- Advantages
dent nature – thanks to AJAX it now incorporates • Better user experience
the logic to handle user actions and transform • Greater responsiveness
them into HTTP requests; the standard Web model • Smaller server load, increased performance
assumes that it’s the browser that dispatches HTTP • Network applications can be updated on-the-fly
requests to the Web server. That is the key concept without redistributing updates
in the solution. Take a look at Figure 1 to see the • Separation of content from presentation (easier
whole interaction process. maintenance)
1. The browser client sends a direct HTTP request Potential Problems
to the Web server (here: the Embedded PL/SQL • Cross-browser incompatibilities
Gateway of Oracle XE); the URL of the request has • Client-side security concerns
been supplied in the location bar or through a
link. The Real World
2. Oracle XE serves a static HTML page that includes Today, AJAX applications are gaining a lot of
AJAX scripts. This static page is then rendered by steam. With Google leading this trend together and
the browser and now all the requests and interac- Yahoo! and Microsoft trailing, the desktop experi-
tion happen indirectly, as AJAX requests. ence is delivered to users through increasingly
3. When the user triggers an event on the Web page dynamic Web pages. Since the early adoption of
by interacting with page elements such as forms AJAX it has matured to be a full-blown solution
and links, an event handler catches it and sends the often chosen by enterprises for commercial solu-
appropriate HTTP request through the AJAX engine. tions.
4. The XMLHttpRequest object requests a remote After the unification of DOM implementations
resource from the Embedded PL/SQL gateway. and the adoption of World Wide Web Consortium
At this point, the user doesn’t have to wait for the (W3C) standards among developers of Web brows-
script to finish fetching responses from the server; ers, it’s now possible to create cross-platform Web
it’s handled in an asynchronous manner. The script applications more easily than ever before. With a
takes as much time as needed to fetch the response wide range of available AJAX toolkits, developers
while the user can further interact with the Web can now upgrade Web applications to an asyn-
page. chronous architecture at a low cost. AJAX is flex-
5. The script performs DOM modifications in the ible enough to be plugged into existing solutions
background while the user can trigger the next and greatly enhances usability. The movement
events on the Web page. of desktop applications to the Web is a matter
You can now upload the attached HTML file of time and represents the next step in software
(hr-ajax-demo.html) into your XE instance through evolution. n

ajax.sys-con.com May 2007 25


Listing 1 ctxt := dbms_xmlgen.newcontext(‘select * from employees where
create or replace function department_id=:DEPT’);
wwv_flow_epg_include_mod_local(procedure_name in varchar2) dbms_xmlgen.setbindvalue(ctxt, ‘DEPT’, w);
return boolean ajax_xmlhtp(ctxt);
is end if;
begin end;
-- return false; -- remove this statement when you modify this /
function
-- Listing 4
-- Administrator note: the procedure_name input parameter may be function ajaxTable(xml) {
in the format: document.getElementById(‘q’).innerHTML = ‘’;
-- var rows = xml.documentElement.getElementsByTagName(‘ROW’);
-- procedure var table = document.createElement(‘table’);
-- schema.procedure var tbody = document.createElement(‘tbody’);
-- package.procedure table.setAttribute(‘border’, ‘1’);
-- schema.package.procedure var tr = document.createElement(‘tr’);
-- for (var h=0; h<rows[0].childNodes.length; h++) {
-- If the expected input parameter is a procedure name only, the if (rows[0].childNodes[h].nodeType!=1) {
IN list code shown below continue;
-- can be modified to itemize the expected procedure names. }
Otherwise you must parse the var th = document.createElement(‘th’);
-- procedure_name parameter and replace the simple code below with th.appendChild(document.createTextNode(rows[0].childNodes[h].ta
code that will evaluate gName));
-- all of the cases listed above. tr.appendChild(th);
-- }
if upper(procedure_name) in ( tbody.appendChild(tr);
‘HR.AJAXE’) then for (var i=0; i<rows.length; i++) {
return TRUE; var tr = document.createElement(‘tr’);
else for (var j=0; j<rows[i].childNodes.length; j++) {
return FALSE; if (rows[i].childNodes[j].nodeType!=1) {
end if; continue;
end wwv_flow_epg_include_mod_local; }
var td = document.createElement(‘td’);
Listing 2 if (rows[i].childNodes[j].childNodes.length!=0) {
create or replace procedure ajax_xmlhtp(ctxt in number) as td.appendChild(document.createTextNode(rows[i].childNodes[j].first-
xml clob; Child.nodeValue));
chnk number := 4000; } else {
begin td.appendChild(document.createTextNode(‘-’));
owa_util.mime_header(‘text/xml’); }
dbms_xmlgen.setnullhandling(ctxt, dbms_xmlgen.empty_tag); tr.appendChild(td);
dbms_xmlgen.setprettyprinting(ctxt, false); }
xml := dbms_xmlgen.getxml(ctxt); tbody.appendChild(tr);
for i in 1..ceil(length(xml)/chnk) loop }
htp.prn(dbms_lob.substr(xml, chnk+1, i+(i-1)*chnk)); table.appendChild(tbody);
end loop; document.getElementById(‘q’).appendChild(table);
dbms_xmlgen.closecontext(ctxt); }
exception
when others then
htp.print(‘<?xml version=”1.0”?>’); Listing 5
htp.print(‘<ROWSET><ROW><INFO>No data found.</INFO></ROW></ <table border=”1”>
ROWSET>’); <tbody>
end; <tr>
/ <th>HEADING1</th>
<th>HEADING2</th>
Listing 3 <th>...</th>
create or replace procedure ajaxe(q varchar2, w varchar2 default ‘’) </tr>
as <tr>
ctxt number; <td>ROW1, COLUMN1</td>
i number; <td>ROW1, COLUMN2</td>
begin <td>ROW1, ...</td>
if q=’count’ then </tr>
ajax_xmlhtp(dbms_xmlgen.newcontext(‘select count(*) “EMPLOYEES” ...
from employees’)); </tbody>
elsif q=’search’ then </table>
i := length(w);
ctxt := dbms_xmlgen.newcontext(‘select * from employees where Listing 6
upper(substr(last_name, 0, :LEN))=upper(:PREFIX) order by last_name’); var request = false;
dbms_xmlgen.setbindvalue(ctxt, ‘LEN’, i); try {
dbms_xmlgen.setbindvalue(ctxt, ‘PREFIX’, w); request = new XMLHttpRequest();
ajax_xmlhtp(ctxt); } catch(e) {
elsif q=’fetch’ then try {
ajax_xmlhtp(dbms_xmlgen.newcontext(‘select * from employees’)); request = new ActiveXObject(“Msxml2.XMLHTTP”);
elsif q=’select’ then } catch (e2) {
ajax_xmlhtp(dbms_xmlgen.newcontext(‘select department_id, depart- request = new ActiveXObject(“MSXML.XMLHTTP”);
ment_name from departments order by 2’)); }
elsif q=’dept’ then }

26 May 2007 ajax.sys-con.com


First Look

Quasar’s Nuqleo System Integrates AJAX into Enterprise Publishing


Work flows improve, bottlenecks disappear when taking a Web-based approach

T
here are a couple of very common issues This notion not only applies to texts, it • Workflow Automation: Nuqleo allows simple
in enterprise publishing, and they almost extends to many aspects of page design as construction of complex workflow scenarios.
invariably lead to bottlenecks. For exam- well. While Nuqleo relies on Adobe InDesign A visual workflow editor lets you combine
ple, if the designer is the only person who can for page layout and typesetting, users with any number of steps and conditional settings
modify a page layout, even minor changes will the appropriate privileges can access design to cover every possible situation.
depend on his or her availability. If only a small files in a browser window and make explicitly • Phonetic Search: Proprietary search algo-
number of people in a workgroup have the pub- authorized changes. rithms can find text even when exact spell-
lishing know-how to prepare a publication for One of the key advantages of Nuqleo is ing is unknown. (This is particularly impor-
the printer, delays are likely to occur. Most enter- that it allows Web-based editing of text and tant in multi-lingual projects.)
prises have learned to live with these constraints design. This means that last-minute design • Visual Tagging: Allows fast access to visual
in their document production because there just changes can be made even when the page information that can’t be captured by key-
doesn’t seem to be a better way. layout application is not present on the com- words.
In the typical publishing workflow, design puter that participates in the editing process. • Integrated Image Management: Nuqleo
modifications can only happen on a worksta- offers centralized picture management
tion equipped not only with the appropriate Flexibility and an Easy with automatic image quality control and
software, but also the necessary fonts for Learning Curve IPTC/XMP metadata support.
a document. Even graphic elements for a Managing collaboration in this way pro- • Translation Management: Nuqleo sup-
page layout are usually stored locally on the vides companies with a considerable amount of ports translation management and can
designer’s computer (very often simply on flexibility, and also allows the administrator to manage alternate designs, visuals, etc., for
his desktop), until the files are prepared and define a system that has minimal training over- local markets.
transferred to the printer or service bureau. head, since only the functionality that is needed • Project Management: Built-in project man-
While this way of working may be accept- to complete a task is exposed to the user. agement tools and a retro-planning mod-
able in small workgroups, it can become The systems can be seen as a toolkit for ule automatically manage documents from
extremely time-consuming when different modern publishing processes rather than start to finish.
departments or offices are involved in the a one-stop solution for magazine, book, or • Publication Management: There are many
document creation. catalog publishers. By opening up very early different ways in which publications can be
on in the development process to the con- represented in the Nuqleo system. Through
A Different Approach siderable complexities of modern enterprise the flatplan manager, a publication can
Quasar’s Nuqleo system takes a different publishing, the company managed to create be displayed and updated in real time in a
approach to solving these problems. By using a system that can speed up the enterprise browser window. Different views let admin-
modern Web technologies such as those com- content publishing workflow significantly. istrators check the status of different sec-
mon to the AJAX approach, the company tions. Inserts and cover-mounted objects
managed to create a completely de-local- Key Aspects are also managed, and a highly realistic
ized, browser-based system that allows users • De-localization: Users from around the preview allows a user to display a publica-
anywhere in the world to access data and world can log into the system and collabo- tion and turn its pages on-screen
documents, to contribute to the publishing rate on a publication.
workflow, and even to modify certain aspects • User Administration: Sophisticated sup- Few providers of dedicated publishing
of a page layout document without needing port for internal users and external con- systems have the necessary understanding
the software or the expertise of a designer. tributors allow an administrator to allocate of the complexities that enterprises face in
While the design files, images, and texts neces- precisely which documents, elements, or their publishing tasks. There is no “typical”
sary for the design process are stored in a central program functions can be accessed by a enterprise, and even less a “typical corporate
server, Nuqleo manages access and user privileges specific user. Nuqleo even manages con- publishing workflow.”
in a sophisticated manner. In other words, if a user tributors who are not allowed access to the Quasar provides a system that offers the
logs in with the necessary privileges to perform system by managing external assignments flexibility and ease of use to be able to tack-
basic text editing, Nuqleo will not expose any via e-mail. le the organizational issues so common in
other aspects of the workflow. This gives the sys- • Web Editing: Most editing operations are con- enterprise content production, collaboration,
tem a lot of security against involuntary changes, ducted directly in the browser. Many aspects of and automation – while also providing the
and it also allows a high degree of flexibility in the a page can be modified without the need for a necessary integration with other systems and
management of documents. page layout application on the host computer. environments if it is required. n

28 May 2007 ajax.sys-con.com


If you thInk thIs Is a
user-frIendly Interface -
let‘s talk

Imagine ajax with a human touch. Where


¬ coding is replaced by designing
¬ development is far beyond ‘trial and error‘
¬ browser compatibility is built-in

Benefit from ajax without coding by working with


Crossvision application designer. The studio and
runtime environment offers easy Web 2.0 develop-
ment and enables rich web applications that match
traditional desktop GUIs in terms of functionality and
usability.

More than 3,000 customers in 70 countries trust


our solutions to maximize the value of their IT.

Software aG
Take The Lead - LeT‘s TaLk!
Free download at www.softwareag.com/ajax
Performance

Fast Scalable AJAX Apps by Dylan Schiemann

Finding and eliminating bottlenecks and bloat

S
uccessful AJAX-based applications provide a ers are optimized for longer-lived connections and
better end-user experience than traditional higher volumes of concurrency than typical Web
Web sites. Fast performance is absolutely servers.
essential to deliver on this potential. The large num- A general rule of thumb with polling: if the
ber of technologies and the additional complexity response time for a request is comparable to that
that AJAX adds to the mix creates significant head- of your polling interval, you’re either polling too
aches in tracking down performance bottlenecks frequently, or your server is taking too long to return
and related issues. useful information.
So where do you start tracking down perfor- The performance of SQL queries is essential to
mance-related problems? The answer is logical: any AJAX application as is the Input/Output (I/O)
by delving into the raw performance data of your performance of your database. Bonnie++ is a use-
application. Perhaps a pedantic suggestion, but by ful tool that helps you quickly track down disk I/O
not adequately analyzing and measuring the data, issues. SQL query performance is the topic of hun-
you’re relying only on hunches and past experience. dreds of articles, but sometimes simple EXPLAIN
Fortunately, we now have a number of highly useful statements and a healthy dose of query log analysis
open source and commercial tools available to assist will suffice to slow or eradicate performing queries.
us in this tedious process. Analyzing performance over the Internet and
The best place to begin a thorough search & verifying that you’re getting the correct data from
destroy mission is with HTTP-level performance the server to the browser is the next step in your
problems that can be resolved in server configura- quest. A number of tools exist to assist with this
tion and fine-tuning. Is the caching configured prop- analysis. Wireshark, formerly known as Ethereal,
erly? Are there issues with load balancing? How many is a network protocol analyzer that provides com-
concurrent requests per server before performance plete insight into all data across the wire for your
suffers? AJAX applications typically reduce the data computer or network. LiveHTTPHeaders, a Firefox
size per request, but highly aggressive polling can extension, allows easy viewing of all normal HTTP
saturate your servers with too many requests. traffic, XMLHttpRequests, and Comet traffic, includ-
When using the Apache Web server, two useful ing the viewing of full headers in the Firefox browser.
open source tools are Apache Bench, which is great Firebug, a debugging extension for Firefox, among
for concurrency testing, and Tsung, which provides its many capabilities, lets you view not only script
Dylan Schiemann is founding software a replay proxy mode to monitor system performance errors and XMLHttpRequest information, but also
engineer for Renkoo and co-founder of under a variety of scenarios. Similar commercial and measures the load times of various resources such as
the Dojo Toolkit. He is best known for open source tools exist for other Web servers as well. script and image files.
building web applications that make use Push the limits of your servers and find out what For those of you waiting for me to get to the
of JavaScript, Dojo, and other common makes them fall down. JavaScript-specific performance optimization tech-
Web development technologies. He is the As AJAX applications become increasingly com- niques, we’ve arrived. With AJAX applications, many
co-founder of SitePen, a consulting firm mon, users expect real-time updates to accompany of our performance issues happen before we even
that specializes in designing custom web their real-time experience. To be effective, real-time get to the code that’s executed in the browser. Now
applications focused on outstanding user or highly collaborative applications require a sig- that you have effectively ruled out issues outside the
experience. Previously, he has developed nificant amount of AJAX polling to make the appli- scope of the Web browser, it’s time to take a closer
web applications for Informatica, Security cation work. If this is simply too demanding on your look at your JavaScript code. If you’re using an AJAX
FrameWorks, and Vizional Technologies, to Web server, you may want to consider switching to toolkit such as Dojo, you may already have profiling
name a few. a Comet server implementation such as Cometd, code to supplement Firebug. For example, a Dojo
dylan@sitepen.com Lightstreamer, KnowNow, or lighttpd. Comet serv- contributor recently found an instance where the

30 May 2007 ajax.sys-con.com


code to create a chart was calling attr.nodeName. large number of small files, provided that you aren’t
toLowerCase() 540,000 times, consuming 15s of time preloading a large amount of code that’s rarely used
at page load! Moving this one line of code inside a by your application. The Dojo package system and
loop drastically fixed the performance of the Dojo build tools solve this problem for Dojo users, and
Charting component. Dojo ShrinkSafe is useful with any JavaScript code.
Looking specifically for code that’s called a lot of For image files, it’s worth considering the con-
times or that takes a lot of time per call are the first struction of image sprites to reduce the number of
places to investigate. Seemingly harmless calls to requests for small image files.
code in your libraries can be expensive operations, Predictive auto-fetching of images is another
especially when iteration, recursion, and/or large optimization technique. This technique was made
data sets come into play, and a quick performance popular by the Google Maps team. In this applica-
profile will expose these resource hogs. tion, images of locations just outside the boundaries
It’s easy to get caught up in the excitement of of the currently viewable map region are loaded in
using a solid JavaScript toolkit, and forgetting that the background after the application has finished
your application doesn’t have to use every feature loading.
provided in your toolkit of choice! And even if the In analysis, it’s important to note that synchro-
toolkit or browser lets you do something, it doesn’t nous requests to a Web server block execution
mean it’s an effective use of system resources. For and give the user the perception of a hanging
example, Dojo provides an excellent aspect-oriented browser. So embracing best practices for asyn-
programming (AOP) advice system for method-to- chronous application development is crucial in
method event connection. However, you should only creating sophisticated Web applications. That said,
be using this when necessary, not in every instance too many concurrent asynchronous requests can
that one method needs to call another one, since the lead to similar issues, so appropriate queuing of
cost for each connect instance is more than a simple requests is a good practice.
method-to-method call. Browser-specific issues are a significant reason for
Assuming that your toolkit has helped you avoid the proliferation of AJAX toolkits. Unfortunately, not
memory leak issues prevalent in Internet Explorer 6, every browser inconsistency is solved by your toolkit
and to a lesser extent Firefox 1.5, there’s still a limit alone. For example, Internet Explorer by default
on the number of objects that can be instantiated in enforces a two-connection limit per server, but it’s
memory at once in any browser before you experi- possible to work around this issue with the clever
ence a significant drag on performance. Our gen- wildcard-masking of aliases. Additionally, caching
eral experience is that Safari 1.2/2 allows the fewest of images loaded by JavaScript in Internet Explorer
number of objects, Internet Explorer 6/7 are better, requires significant workarounds when your appli-
and Opera and Firefox are significantly better than cation design contains many image files. Browsers
that. It would be great to see a quantitative study that literally have thousands of quirks and idiosyncrasies,
compares the memory consumption and relative so starting with a good toolkit and regularly reading
performance limits of object instantiation. developer blogs and Web sites will keep you “in the
In further evaluating browser performance, you know” on the latest workarounds.
should be looking for expensive operations that Given that AJAX applications are intended to be
cause CPU spikes, excessive memory consumption, faster and more feature-rich than traditional Web
or leaks, and seek out alternative or more efficient sites, it’s imperative that speed and performance
approaches. Unfortunately, each major browser’s aren’t lost in the excitement of adding new capa-
JavaScript and DOM implementations are different, bilities to your existing app. I’ve only scratched the
and what works well in one browser doesn’t neces- surface of what’s required and what’s possible in
sarily perform well in another. optimizing performance, but with a little patience, a
When looking at the initial page load time, sig- good set of tools, and an understanding of HTTP and
nificant consideration should be given to the num- current browser issues, you’ll have a good process to
ber of requests and the size of each request being begin eliminating performance issues before they
made on the server. One large file is preferable to a turn into performance nightmares. n

ajax.sys-con.com May 2007 31


Inside Look

Pushing AJAX into High Gear


A simple streaming AJAX example with the by Kevin Hakman and Joe Walker

OpenAjax Hub, TIBCO GI, and DWR 2.0

F
ollow along and implement the real-time TIBCO General Interface, an open source AJAX proj-
streaming AJAX system in Figure 1 using two ect that currently provides ready-made AJAX controls
different AJAX toolkits and the OpenAjax Hub. for GUI, data, and communications in addition to
visual tools for rapid AJAX application development,
Requirements unit and functional testing, and AJAX debugging.
The requirements for this solution are straight-
forward. For this application we need a ready-made Real-Time Communications
data grid control that will display changes in prices For our real-time data, we’ll use DWR 2.0, the
to stocks when those changes occur. A nice-to-have just-released next version of Direct Web Remoting
would be visual indicators in the GUI that show (DWR), an open source project that enables you
when a cell value in the grid is increasing or decreas- to remote Java objects through JavaScript in the
ing…and, of course, we want to deploy this to just browser and now vice versa through its “Reverse
a standard Web browser, so we also must do this AJAX” capabilities for real-time remote control of
without any reliance on plug-ins, applets, or Active- JavaScript objects in the browser via Java objects
X controls. (Thanks goodness this is an AJAX article!) on the server across a persistent HTTP connection
Figure 1 shows the basic design that could be styled (a.k.a “Comet”).
more at a later date. In addition we’ll want to add
more AJAX controls to this page that can tap the Project Source Code
same streaming stock data for other calculations and You can quickly grab a copy of this project and all
visuals, such as charts or portfolio totals. For now, its parts from the 2.x release of DWR at http://geta-
we’ll keep it simple. head.org/dwr. Once you’ve installed DWR, check
out the General Interface demo. Those who want to
Architectural Design extend the GUI and add more controls should also
We don’t have to build the above system from download TIBCO General Interface from http://
scratch, and can instead leverage readily available, developer.tibco.com/gi. Note that the OpenAjax.js
reusable AJAX parts to get the job done quickly; the file that ships with the project in the DWR down-
architectural strategy is to use AJAX pieces and parts load is an older, 46 kb version of the OpenAjax Hub.
that can work together. At the core of the system in The latest version of the OpenAjax Hub, which now
Figure 2 is the OpenAjax Hub (see the OpenAjax Hub also implements a savvy topic-based event naming
for Interop sidebar). We’ll use the OAA Hub as a cen- scheme over the basic pub/sub capability, is cur-
tral publish/subscribe bus to which we can publish rently under 2 kb (yes two kilobytes – that’s not a
the live stock data so that the data grid and the future typo).
visual controls and functions can listen for those
events and messages. Implementation
The <dwr>/gi/index.html file loads up the
Resources OpenAjax.js file, the needed DWR libraries, and
Publish/Subscribe Core some application specific files in the head of the
For our publish/subscribe core we’ll use the HTML page.
OpenAjax Hub, an open source project implement- The body of the page includes a div that loads the
ing the evolving OpenAjax Alliance Interoperability TIBCO GI library.
Working Group specifications. Start at HYPERLINK
Kevin Hakman is the co-founder of General “http://www.openajax.org” www.openajax.org and <div style=”width:100%; height:220px;”>

Interface and director of developer evange- follow the links to the sourceforge.net project from <script

lism for TIBCO Software Inc. there. type=”text/javascript”

src=”JSX/js/JSX30.js”

Joe Walker is the creator of DWR and presi- Ready-Made GUI Controls jsxapppath=”gidemo” jsxlt=”true”> </script>

dent of GetAhead Ltd, UK. For the GUI controls we’ll leverage those from </div>

32 May 2007 ajax.sys-con.com


// But we are going for a fancy option that ScriptProxy proxy = new

The jsxapppath=”gidemo” loads the GI does highlighting ScriptProxy(sessions);

project in /gidemo and in turn renders the for (var property in corporation) {

GUI component declaration: gidemo/compo- if (property != “jsxid”) { Corporation corp = corporations.get-

nents/appCanvas.xml. Once these are loaded, var ox = matrix.getContentElement(corp NextChangedCorporation();

GI’s project init function is called: oration.jsxid, property); proxy.addFunctionCall(“OpenAjax.publish”,

if (ox) { “gidemo”, “corporation”, corp);

function giLoaded() { var current = ox.innerHTML;

OpenAjax.subscribe(“gidemo”, “corporation”,

objectPublished);

dwr.engine.setActiveReverseAjax(true);

This subscribes to the OpenAjax Hub lis-


tening for publications to the ‘gidemo’ + ‘cor-
poration’ topic. When a publish happens, the
objectPublished function is called. The last
line turns DWR’s Reverse AJAX on so that the
data can flow from the server to the client
without polling or waiting for the GI applica-
tion running at the client to request an update
from the server. The objectPublished function
looks like this:

function objectPublished(prefix, name, han-

dlerData, corporation) {

var matrix = giApp.getJSXByName(“matrix”);

var inserted = matrix.getRecordNode(corpor

ation.jsxid);

matrix.insertRecord(corporation, null,

inserted == null); Figure 1: Web-based real-time stock quotes implemented using TIBCO General Interface,
matrix.repaintData();
the OpenAjax Hub, and the recently released DWR 2.0.
}

if (current != “” + corporation[property]) {

This simply takes the published data and ox.style.backgroundColor =

inserts it into the GI matrix component. Each “#FDE4EB”;

column of the matrix component is bound var callback = function(ele) {

to a property of the corporation JavaScript return function() { ele.style.

object. The matrix control, its columns and backgroundColor = “#FFFFFF”; };

bindings were configured using TIBCO GI’s }(ox);

visual tools: TIBCO General Interface Builder. setTimeout(callback, 1000);

There are a number of possible repaint ox.innerHTML =

strategies, including the simplest of them corporation[property];

all: matrix.repaintData(); as shown above. }

However, to meet our requirements above, }

in the source below we’ve implemented a }

more sophisticated approach that enables }

both incremental painting of updated rows ...

and cell highlighting.


Instead of matrix.repaintData(); we’ve Meanwhile, on the server the following
used this: Java code is running in a thread:

... while (!Thread.currentThread().isInterrupt-

// There are many ways to get a table to ed())

repaint. {

// One easy way is to ask it to repaint: Collection sessions = serverContext.

// matrix.repaintData(); getScriptSessionsByPage(“/dwr/gi/index.
Figure 2: System Architecture
html”);

ajax.sys-con.com May 2007 33


int timeToSleep = random.nextInt(2500); push JavaScript to these users. The ScriptProxy
Thread.sleep(timeToSleep); This simply finds the people viewing this is a feature of DWR 2.0 enabling DWR 2.0 to
} page and creates a ScriptProxy to allow us to dynamically generate JavaScript from a Java
API. This is done at runtime rather than com-
pile time, so we can use it to remote control
OpenAjax Hub for Interop many browsers. This makes it very easy to write
Two months ago in New York, immediately following AJAXWorld East 2007, the OpenAjax things like chat applications, or anything par-
Alliance met and held its first InteropFest where a handful of the more than 75 industry ticularly dynamic. Messages are sent to clients
members of the nascent AJAX standards organization demonstrated their technologies across using DWR’s “Reverse AJAX” capability.
working in context of the first specification project of the alliance – the OpenAjax Hub We then ask the corporation’s object for
(OAA Hub). If you haven’t been watching the evolution of this specification targeted at a Stock price change, and publish this to the
enabling AJAX libraries and controls to be interoperable, it’s rather interesting that at the Open Ajax Hub.
core of the OAA Hub is a publish and subscribe event and message bus leveraging the That’s it. Pretty simple.
tried and true interoperation approaches typical of server-side integration strategies, but For the full source to all the files, including
instanced on the client side. the TIBCO GI project files, see the source in
Why is a “pub/sub” system at the core of the standard interoperation strategy for AJAX? the .war file download for DWR 2.0.
With increasingly sophisticated AJAX software, mashups, and composite applications
being built today, the pub/sub strategy makes developing such things simpler. Consider Other AJAX Controls
that when you have a system consisting of more than one part, and especially in such Changes to Java Objects are sent to DWR
systems that may grow and change over time like mashups, portals with AJAX portlets, 2.0’s Reverse AJAX connection, and converted
or composite applications, instead of writing procedural code for each part of the system to JavaScript by DWR. In this case, the convert-
that needs to work with another (which as you CS majors know, leads to the classic “n- ed objects are wrapped in the OpenAjax Hub’s
squared” integration complexity problem), it’s far more efficient to implement a system publish method so that when the pushed
for receiving, then dispatching events and messages so that one part can publish an event code arrives at the client, the OpenAjax Hub
through the intermediary pub/sub hub, and then other parts that need information from publishes the data to a message topic name.
that system can implement specific listeners that subscribe to, receive, and handle the The JavaScript Objects, such as the TIBCO GI
events and messages. matrix GUI component, are coded to listen for
new information on that topic and, in turn,
handle the new information when it arrives.

Conclusion
The solution above demonstrates how
easy it can be to implement powerful systems
based on sound publish and subscribe archi-
tectural principles. Further, the decoupled
nature of the publish and subscribe style
implementation enables one piece of a sys-
tem to be added or replaced without effect-
Figure 3: Comparison of a system of separate parts, integrated point to point versus a ing other parts. Accordingly, this approach is
system integrated based on publish/subscribe events and messages. highly applicable to mashup and AJAX portal
scenarios. As shown, beyond the basics of
using the emerging publish and subscribe
As opposed to the more primitive DOM events such as onclick, onkeydown, standards of the OAA Hub to connect reusable
onmouseover, and the like, typically these types of events and messages are associated client-side components, technologies, such
with “application-level” concepts such as like “userLoggedIn”, “newCustomerCreated”, or as DWR 2.0’s Reverse AJAX and TIBCO’s just
“addNewStockSymbol”. released Ajax Message Service for highly scal-
Figure 3 compares a system with five parts directly linked to each other in a point-to- able real-time data over HTTP, are enabling
point fashion with a system implemented in a publish/subscribe message bus architec- publish and subscribe events to occur across
ture. the network. Accordingly, one can begin to
Architecting your AJAX applications using publish and subscribe techniques enables think not of an HTML page in a browser
each part of the system to be decoupled from the others, and thus to be built and managed connected to a server across a network, but
as distinct units. This modularization not only facilitates greater reuse and more efficient instead the AJAX application running in the
team development, but also helps you to avoid creating the hairballs of code typical of browser being in the same event cloud as the
point-to-point architectural approaches to application systems. The more elements in a server, publishing to and subscribing from
system, the most complex and expensive adding to and maintaining the system becomes streams of information mediated by event bus
in point-to-point architectures when compared to publish/subscribe bus architectures. architectures on the client and on the server,
and, accordingly, enable you to build more
powerful AJAX solutions. n

34 May 2007 ajax.sys-con.com

Vous aimerez peut-être aussi