AJAX & Rich Internet Applications

Bringing Interactivity & Intuitiveness Into Web Applications

AJAX Defined
• Asynchronous Javascript and XML • Ajax is not a new technology
– Term coined by Jesse James Garrett – www.adaptivepath.com

• A bundle of techniques
– – – – –

– Google calls their technique: Javascript – Also known as XMLHTTP technique – In use since at least 1997

Mr. Ajax

• Core techniques are centered around asynchronous communication to the server without a page refresh

Some are pure – XML data interchange only Some are not – Passing Javascript methods to client Some are cool – DHTML widgets Some are not – XML & XSLTs Ok..they’re all cool…


Traditional Web Applications…

Pick An Item
‘Add To Cart’

Action Validation Persistence Forwarding

Review Cart
Enter Data Submit

Action Validation Persistence Forwarding

Enter Shipping
Enter Data Submit

Pages & Actions
Error Page
‘Can’t Order 500’

Action Validation Persistence Forwarding

Client code concerned with validation Submits sent to actions Actions perform work and then forward to next page Page refresh for each submit

Unit of work is a page

Enter Billing
Enter Data Submit

AJAX Changes How Web Apps are Built
Components & Events
Order Entry
Item List (DIV) ErrorViewer (DIV) Events/Actions Validation

Item List Component Shopping Cart Component Shipping Component Billing Component


Shopping Cart (DIV) Shipping Form (DIV) Billing Form (DIV)

Persistence Event Handlers GUI Creation

Unit of work is a component Three-Tier Client/Server Model Client code has validation, flow, layout, data interchange No submit buttons—save buttons Only parts of pages are updated at a time


AJAX Enabled Master Detail Form

No screen flicker. Individual regions or fields updated. Client sends data to server asynchronously. Server returns data, messages, gui, or code.

Two ways of talking to the server…
• XMLHTTPRequest object
– – – – – Allows for asynchronous GETs + POSTs to the server Does not show the user anything—no status messages Can have multiple XMLHTTPRequest active at one time Allows you to specify a handler method for state changes Handler notified when request is: • Initialized • Started • In the process of being returned • Completely finished – Originally only available for Microsoft IE – – – – – – – IFRAME is a “mini-browser” window in an HTML document Can be hidden (0 width, 0 height) IFRAME can call a URL Javascript can read the contents of the IFRAME User sees messages on status bar Hears a click as server submits request Much slower than XMLHTTPRequest



XMLHttpRequest Object: Methods
• open(“method”, “URL”) • open(“method”, “URL”, async, username, password)
– Assigns destination URL, method, etc.

• send(content)
– Sends request including postable string or DOM object data

• abort()

– Terminates current request – Returns headers (labels + values) as a string

• getAllResponseHeaders() • getResponseHeader(“header”)
– Returns value of a given header

• setRequestHeader(“label”,”value”)
– Sets Request Headers before sending

XMLHttpRequest Properties
• onreadystatechange
– Event handler that fires at each state change – You implement your own function that handles this 0 = uninitialized 1 = loading 2 = loaded 3 = interactive (some data has been returned) • This is broken in IE right now – 4 = complete – HTTP Status returned from server: 200 = OK – String version of data returned from server – XML DOM document of data returned – Status text returned from server

• readyState – current status of request
– – – –

• status

• responseText

• responseXML • statusText


Message Flow
<script type=“text/javascript”>
Message name=steve Or <name>Steve</name>

Validation Servlet ValidateName( req, res…) { parse request lookup name in database is it valid? if so, return OK otherwise return error message

function handleResponse() { …read response from server …get a handle to the DIV If Not OK Replace DIV contents with msg } function checkName( name ) { …initialize request (url, parms) …register callback function …call the server }

Message status=999 msg=Not a valid name

<div id=status Not a Valid Name >



Message Flow
<script type=“text/javascript”> Validation Servlet: /validate _ajax.send( some data ) Get parameters…do some work Return something… a text message an XML document an HTML snippet a javascript method whatever you want…

function doResp() { if _ajax.readyState == 4 and _ajax.status != 200 { div=document.getElementById(‘status’) div.innerHTML = _ajax.responseText;
Message status=999 msg=Not a valid name

Save button onchange event: _ajax = new XMLHTTPRequest(); _ajax.onreadystatechange = doResp; url = ‘./validate?field=’ +this.name+‘&value=’+this.value; _ajax.open(‘GET’, url, true )

Steve Save
<div id=status Not a Valid Name >




Security Issues
• You can only hit the domain that the original web page came from • Because of this, the AJAX technique cannot normally be used to access a Web Service of a 3rd party server
– You can wrap those requests through your own server – You can allow XMLHTTPRequest to access specific sites in your browser security settings

• IFRAME can be used to access any site if needed

Lets Look at Some Code!
• • • • • • Ping Example 10 Sequential Pings Big File Example onchange Example onkeypress Example DropDown handling
– Auto Form Filling – Retrieving Form Data – Form Posting via AJAX

• Form Handling • DIV replacement
– via text – via XML

• Google Suggest Example


Wow..I didn’t know soccer teams did web programming..

How It Works
• Fires roughly every keystroke
– Uses a timer to determine when to send a request to the server – If you type at “typical” user typing speed—every keystroke – If you type at “programmer” typing speed—every few keystrokes

• Creates a hidden DIV that is shown when you start typing • DIV is populated with return results from server • Text field is set to include the next word from the server list and everything to the right of the cursor position is highlighted
– If you hit the right arrow, it assumes you want that text and positions you at the end of the text field

• Results cached; if you backspace, server is not called again • Has a timer adjustment to increase or slow down server calls
– Slow dialup sessions hit server fewer times – Fast broadband hits a lot


JavaScript Returned
sendRPCDone( frameElement, "the k", new Array("the killers", "the knot", "the killers lyrics", "the keg", "the kills", "the kinks", "the killers band", "the kite runner", "the king and i", "the killers hot fuss"), new Array("5,980,000 results", "5,050,000 results", "339,000 results", "1,580,000 results", "10,800,000 results", "1,350,000 results", "876,000 results", "204,000 results", "25,100,000 results", "388,000 results"), new Array(""));

So…is this here to stay?

They said go EJBs…then they said WSDL…now AJAX?


So why is AJAX so hot—NOW?
• Demand for richer applications is growing • It has a name
– Broadband means we can—and want to—do more – Think LAMP – Google gmail, Google suggests, Google Maps

• Recent Google applications have sparked people’s imagination • Every year for the past 3 or 4 years has been the “year of the rich client”
– I think its time…

• People are thinking of building APPLICATIONS…not just sites • The Tipping Point
– All of this has made rich internet apps reach its tipping point— where adoption spreads rapidly and dramatically

Rich Internet Apps Will Be Around A Long Time

Users Like It A LOT


Some people don’t like AJAX…

What’s Not to Like…
• You have to program in Javascript
– Need libraries + frameworks to make it easier

• You have to program against the browser DOM • Lots of HTTP requests to server
– Requests are smaller however – Total bandwidth may not go up – Differences between browser implementations

• If you want client/server, why not use a real client/server system?

• Testing

– .NET can access Web Services on your Java boxes – Why not Flash/Flex? – Tons of good third-party rich client systems

• No Back Button

– Cross-browser quirks – New browser versions – Is this a bad thing?


Things To Consider…
• • • AJAX requires a different way of thinking about how you build your application Requires thinking about interface and interaction How do you handle state + sessions?
– – – – – – No cool GUI tricks for the sake of doing cool GUI tricks Usability is the key—and is what you should strive for The issues we had in the client/server world are back Decision on where to put state information gets trickier Can all be on the client so you can have truly stateless servers Requires a lot more client code for state – server already has mechanism for clustered state synchronization What happens if the server or network dies? Refresh button can kill your app – open your application with minimal chrome Back button is meaningless unless you code ‘undo’ functionality to it Bookmarking doesn’t work unless you manually change the URL Sending each keystroke for field validation is a pretty dumb idea actually Even sending each field—wait till the user is ready to send with a SUBMIT or SAVE button

Navigation Issues
– – – – –

Don’t assume the server is going to respond instantly

What about the Back button?

Next topic please


What about the Refresh button?

Next topic please

Back & Refresh Buttons
• Back Button

• Refresh Button

– Make it work as an undo? – Save state in <body onload> method?

• Or, make it a non-problem

– Open your “application” in a window without toolbars – Capture the F5 Key – Capture Control-R

• You will hear people get hysterical about this

– “Browser is the user’s domain—work around it—code for it” – If your site is a public site then this is basically valid – If you are building an application for users to run then strict web rules are off the table


AJAX will be around for a long time…
Users are demanding Rich Internet Applications AJAX + Tools + Framework + Controls = Rich Internet Apps

• No new infrastructure needed
– Utilize existing skills

• Much richer GUI than today
– Meets most users needs for responsiveness – Much faster response times

• • • • •

No distribution hassles Cross-Platform Browser Support Reduced bandwidth utilization Grass roots developer interest & support Vendors implementing AJAX frameworks
– ThinkCAP has it now…as you will see later…

• Developer sites + open source frameworks

AJAX Patterns
• Change Browser Content with the DOM • Remote Scripting
– Return HTML or XML and change named items • Usually DIVs or SPANs – Execute business functions on the server from the client – Using Timers to ping server on regular basis – – – – – Populate SELECT list Pass target DIV to replace to the server Instant Validation as User Works SAVE instead of SUBMIT CANCEL instead of BACK

• Events & Scheduling

• Specialized Functions to perform common GUI tasks

• DHTML Techniques
– CSS, Drag & Drop

• Server-Side Code Generation
– Return Javascript to client


Common Widgets • • • • • • • • • • Form Validation Interactive Grids Drilldowns TreeViews Auto Completion Application Status Area Progress Bars Dynamic Lists Tabs AJAX’ed Portlets Predictive Fetch

AJAX Frameworks
• Pure JavaScript Framework
– Infrastructure • Provides basic piping & portable browser abstractions • Content up to developer • Typical Functionality:

– Application Framework • Includes basic Infrastruture functionality

– Wrapper around XMLHttpRequest – XML manipulation & interrogation – DOM manipulations based on responses from XMLHttpRequest

• Server-Side Framework

– HTML/JavaScript Generation • Server provides complete HTML/JS code generation and browser server coordination • Browser-side coding is for customization – Remote Invocation • JavaScript calls routed directly to server-side functions (Java Methods) and returned back to Javascript callback handlers


Pure JavaScript
– – – –

Pure JavaScript Infrastructural
– – – – – – – –

DOJO (9/04) Prototype (2001) Open Rico (5/05) Qooxdoo (5/05)

Server-Side (Multi Language)
– – – – – – – – –

AjaxJS (5/05) HTMLHttpRequest (2001) Interactive Website Framework (5/05) LibXMLHttpRequest (6/03) RSLite Sack (5/05) Sarissa (2/03) XHConn (4/05)

Pick a Framework… any Framework

Server-Side (Java)

Cross-Platform Asynchronous Interface Toolkit (5/05) SAJAX (3/05) Javascript Object Notation (JSON) & JSON-RPC Javascript Remote Scripting (2000) Echo2 (3/05) Direct Web Remoting (DWR) (2005)] ThinkCAP Minerva (04/2005) CL-Ajax

• • •

Server-Side (Lisp)
Ajax.NET (305)

Server-Side (.NET) Server-Side (PHP)
– – – – AjaxAC (4/05) JPSpan XAJAX

Server-Side (Ruby)


Ruby-On-Rails (3/05)

Sites of Interest
• www.ajaxmatters.com • www.ajaxian.com • www.ajaxpatterns.org • Foundational Libraries
– Prototype • very OO foundation to manipulate XMLHTTPRequest • Core of “Ruby on Rails” AJAX implementation – OpenRico • Builds on Prototype, adds some controls • Nice “effects” library to zoom/fade/shrink GUI elements – Sarissa • Heavy duty XML library for XSLT – SAJAX & XAJAX • PHP libraries with some good ideas • Server driven JS creation


Our AJAX Implementation & Experience

AJAX will change web development

AJAX represents a fundamental shift in how web applications are built We’ll be building 3-Tier Client/Server applications with AJAX
• • • • • Users want enhanced, interactive functionality They want their data easily accessible and maintainable They don’t want screen flicker They don’t want over-the-top GUI—just functional Once they see an AJAX application—they want it now


What is needed to build real AJAX apps?
• AJAX needs tools for productive development
– – – – Lots of moving parts needing organization Javascript, DHTML, Async Communications, Server Code Event driven coding benefits greatly from visual environment Need to reduce amount of Javascript to write

• AJAX needs libraries
– – – – – – Javascript communication library Cross-platform compatibility AJAX data marshalling library Visual controls & effects libraries Server support & data binding libraries Error handling

ThinkCAP: Transactional AJAX Framework
• Problem
– – – – Developers hand code data access No provisions for error handling No data binding mechanism Need to handle nested transactions

• ThinkCAP Solution
– Built to support transactional business applications – Data binding & form generation – Master/detail record linkage – Declarative transaction boundaries on components – Standard error handling routine – TransactionSafe™ eliminates database connection leaks – Javascript generation for most common tasks


ThinkCAP: 3-Tier Client/Server Event Model
• Problem
– Developers hand code Javascript events

ThinkCAP Solution
– – – – –

Integrated & tested three-tier client/server event model Executes event logic on client or server Over 25 response methods minimize hand-crafted Javascript Advanced context & response management Drag & Drop Events
public ClientResponse zipcode_change(ClientContext con) { ClientResponse response = new ClientResponse(); String zipCode = con.getFieldValue(); if ( !isValidZip(zipCode) ) { response.alert(‘Zip Code is not valid.’); response.select(‘zipcode’); response.setFocus(‘zipcode’); … more code …

ThinkCAP: Advanced Controls & Effects
• Problem

– Rich Internet Apps need controls for richness. DHTML Javascript is complex and tedious.

ThinkCAP Solution

– Library of customizable dataaware GUI control & effects

Advanced Controls
– – – – – – –


Outlook Bar Dynamic Tabs Accordion TreeView Updateable DataView Edit Masks Autocomplete Field

– Fade in, out – Slide up, down


ThinkCAP: Best of Breed Open Source
• Problem

– Integrating open source frameworks is time consuming and expensive – Many RAD frameworks & libraries are completely proprietary

ThinkCAP Solution

– ThinkCAP integrates over 20 open source libraries – Based on Struts • You to rapidly AJAX enable Struts applications • Existing Struts apps run ThinkCAP w/o modification • TagLibs for ThinkCAP components • Struts XML/Page Flow Designer – Visual designers for metadata • Hibernate & Castor Designers • Business Chart Designer (JFreeChart) – Declarative logging through Log4J – Apache Commons Validator Server Validation – Prototype.js and OpenRico used for core client framework – Integrates with Eclipse; via plug-in

Hibernate/Castor Designer

ThinkCAP: Integrated Visual Workbench
• Problem
– Tedious coding of HTML and Javascript is non-productive – High levels of expertise needed to hand-craft – Most tools focus on low-level J2EE features vs. productivity

ThinkCAP Visual Workbench
– – – – – – Highly Productive & Intuitive Built for Business App Developers Robust Page Layout Designer Drag & Drop Form Designer Advanced DataView/Grid Designer Eclipse IDE Integration


A complete environment for web development
• • • • • • • • • Visual Design Environment Page Flow Designer Smart Data Binding Integrated Persistence Engines 3-Tier Client/Server Event Model Advanced Controls & Visual Effects Struts & Open Source Based Eclipse Integration Runs on any application server