How You Can Use To Create More Powerful, Real-time Web Applications

Presentation by: Duncan Kenzie, CTO BCD Software International November 3, 2005

www.bcdsoftware.com AJAX The Acronym

AJAX = “Asynchronous Javascript and XML” Term coined earlier this year by Adaptive Path See these links: http://www.adaptivepath.com/publications/essays/archives/0 00385. and: http://en.wikipedia.org/wiki/AJAX

Don’t Worry About The Fancy Acronym XML is not essential to use AJAX Some Javascript is “Asynchronous” is core concept

AJAX is being popularized by Google

www.bcdsoftware.com FAQs On AJAX

Q: Is AJAX New? A: Not really The term is relatively new (Feb 2005) Technology available in IE browsers since 1998 in browsers have been there for several years to take advantage of AJAX. For example, you could use it with IE browsers since 1998. Q: Can I Use AJAX on my iSeries? A: Absolutely! Q: Do I need to install anything on my iSeries to use AJAX? A: Nope! Q: Is AJAX supported in FireFox and IE? A: Yes- it’s supported by all the major browsers

www.bcdsoftware.com So What Does AJAX Do For Me?

Classic User/Server interaction Model in Browsers: Kinda like 5250 – the server knows nothing until the User hits Enter: User requests page Server delivers entire page User clicks ‘OK’ Server responds – probably delivers another or same entire page.

AJAXIAN Model: Kinda like Client/Server ! User does something – anything Eg: mouse click, types a character, moves mouse, etc. Server responds Some browser content is updated (asynchronously) – part of page or whole page

www.bcdsoftware.com But Wait! I Hate Client/Server !

Of Course You Do! And Rightly So! Client/Server apps are a pain to distribute – you have to make sure the client code is always in synch with the server Client/Server apps are ‘heavy’ – huge client codebase to execute!

But – AJAX uses key benefits of Client/Server without the downsides! No Heavy client – just intelligent web pages containing lightweight scripts No Distribution issues – everyone has a browser, and the client-side code is self-updating (ie every time you visit a page it updates) You get REAL-TIME INTERACTION between the User and the Server!

www.bcdsoftware.com Real-Time Interaction with AJAX

This Is The Core Benefit and the reason AJAX will transform Web Applications in the next 2 years

Your applications can respond immediately to user input You can control subsequent page content based on user responses You can distribute and optimize server workload by having the server return many small amounts of data to browsers instead of less frequently returning huge amounts (entire pages) You can create more ‘intelligent’ applications Your users may not even realize they are interacting with the server

www.bcdsoftware.com Possible Uses For AJAX

Web-Based Instant Messaging AJAX call every n seconds to poll server for new messages Call takes place in background, with user unaware it is happening More Intelligent Searches AJAX call on every user keystroke in a search field Server returns a subset of hits that becomes more refined with each keystroke Eg: Google Mail, Google Suggest More Intelligent Forms Completion AJAX call to retrieve customer data (name, address, etc.) and update part of page once user has typed a valid customer name AJAX call to refine list of state names based on abbreviation typed by user AJAX call to show or hide parts of a form based on evaluating on the server a user’s response

www.bcdsoftware.com Another Example

Google Maps: As you move around or zoom in on an area of a map, an AJAX call in the background retrieves an updated image from the server and returns it to the browser, without a page refresh This happens asynchronously- you can continue moving around the map while the server sends updated info to the browser in the background. Eventually, the two catch up with your mouse movements. This would be impossible to do using the classic browser- server interaction model.

www.bcdsoftware.com Other Examples

To do list Add, change, delete items without reloading page Drag and drop components on page For portal technology – design pages easily Folder trees Access server as nodes are open, rather than loading entire tree from server on each page load Better communication with user Send ‘I’m busy’ messages to the user while the server does something in the background

www.bcdsoftware.com Google’s Gmail –Ease of Use

Old way of composing email Click the ‘Contacts’ button Type the search value, or click on a letter of the alphabet to narrow your search Click the ‘search’ button Scan the list and click on the contact’s email address. At least 4 steps, assuming you find the address first try. Google way You start typing the recipient’s name or email address (even if this is just a guess) Google immediately responds to EACH CHARACTER YOU TYPE and pops up a dynamic list showing you the possibilities. If you see the one you want, you select it by clicking on it. If not, you keep typing. 2 Step process – and much easier find functionality

www.bcdsoftware.com How Does Google Do This?

At first, you might think, ‘Well, they’ve simply loaded my entire address list into a Javascript array on my page, and then a nifty bit of script scans that array’. But think of the load on the server, and the possible size of the page to do this – if you have hundreds of addresses, this means hundreds of database accesses and writes to the page initially, and that’s before you’ve even decided for certain that you really want to compose an email ! In reality, what Google does is to make a server call to access your address book only once you start typing and for every character you type . At this point, they can narrow down the possible choices with a routine that matches on the potential recipient’s name and/or email address. Incidentally, Gmail only returns 15 hits at a time. The theory is that as you keep typing, and the list is updated accordingly, you will eventually find the correct address.

www.bcdsoftware.com What About Server Workload?

Q: Does making a round trip to the server on each keystroke place an excessive load on the server? A: Not necessarily – Alternative is to load entire address list (in my case, over 300 names) each time the user wants to compose an email Each keystroke returns only 15 hits In my experience, it takes a maximum of 3 keystrokes to find my intended recipient That’s 3 server calls for a total of 45 database hits

www.bcdsoftware.com Google Suggest

Visit http://www.google.com/webhp?complete=1&hl=en Works like GMail: Makes AJAX requests to server as you type Returns list of suggestions for each combo of characters you type

www.bcdsoftware.com Google Suggest – Type ‘m’

www.bcdsoftware.com Google Suggest – Type ‘mi’

www.bcdsoftware.com The Hidden IFrame Trick – Don’t Use It!

IFrames provide a way for the client to call the server in the background This is one method of implementing ‘AJAX style’ technology BUT – it has the following weaknesses: Relies on hidden HTML elements embedded somewhere in page – violating rule of separating layout from function Browser is inefficient in loading IFRAME content The user gets an annoying ‘click’ when hidden iframes make a server call – a source of confusion, at least. Support for asynchronous communications is weak

www.bcdsoftware.com The Heart of AJAX - XMLHttpRequest

XMLHttpRequest Browser component Available in Mozilla Firefox as a native object Available in IE as a ‘native’ ActiveX In IE browsers since 1998 Use it by writing Javascript code in your web page You can create an external Javascript file that embeds most of the AJAX functionality Good technical reference: http://developer.apple.com/internet/webcontent/xmlhttpreq.html

www.bcdsoftware.com XMLHttpRequest Conversation

Containing Web Page

Script Area XMLHttpRequest Object

Javascript Function Server Code

(CGI program User Input Input Box or Java servlet, etc.) New Page Content

Presentation Area (HTML etc.)

www.bcdsoftware.com XMLHTTPRequest Object Details

Methods: Open - Assigns destination URL, method, and other optional attributes of a pending request Send – Sends the request (as a URL), optionally with postable string or any page contents Events: Onreadystatechanged – Fired when Object’s ‘ready state’ changes – usually as a result of a Send method and server response Properties: readyState – value of 4 = ready Eg: if (xmlhttp.readyState != 4) return; Status – Numeric code returned by server: 200 = Successful 404 = Not Found Eg: if (xmlhttp.status == 200) // OK responseText – Contains response from Server in non-XML format responseXML -DOM-compatible document object of data returned from server

www.bcdsoftware.com Code to Create XMLHTTPRequest Object var _ms_AJAX_Request_ActiveX = ""; // Holds type of ActiveX to instantiate – Global variable. function AJAX_Update(url, obj, func) { // code for Mozilla, etc. if (window.XMLHttpRequest) { var xmlhttp=new XMLHttpRequest(); // XMLHttpRequest is Mozilla (FireFox) Object } // code for IE else if (window.ActiveXObject) { // Instantiate the latest MS ActiveX Objects – ms_AJAX_Request_ActiveX is Microsoft Object if (_ms_AJAX_Request_ActiveX) { xmlhttp = new ActiveXObject(_ms_AJAX_Request_ActiveX); } else { // loops through the various versions of XMLHTTP to ensure we're using the latest var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < versions.length ; i++) { try { // try to create the object. If it doesn't work, we'll try again // if it does work, we'll save a reference to the proper one to speed up future instantiations xmlhttp = new ActiveXObject(versions[i]); if (xmlhttp) { _ms_AJAX_Request_ActiveX = versions[i]; break; } } catch (objException) { // trap - try next one } } } }

www.bcdsoftware.com Calling the XMLHTTPRequest Object – Part 1

// … Code from previous slide to instantiate AJAX object // (Continuation of AJAX_Update object).

xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState != 4) return; if (xmlhttp.status == 200) func(obj, xmlhttp.responseText); else alert("An error occurred" + http.status); }; else xmlhttp.onreadystatechange = function() { return; }

xmlhttp.open('GET', url, true); xmlhttp.send(null); if (func) {} else return xmlhttp.responseText; return false; }

www.bcdsoftware.com Calling The XMLHTTPRequest Object – Part 2

HTML: Type Email Address:

Event Handler: function handleKeyUp( e , divname ) { // … Code to handle characters typed by user. // User typed some characters: if (target.value) {

var myurl += “ajaxdemo.pgm?task=search&key="+target.value; // Fire request for data and populate div: AJAX_Update(myurl, divname, AJAX_Response); } }

// Called from inside the function AJAX_Update: function AJAX_Response(mydiv, response ) { mydiv.innerHTML = response; }

www.bcdsoftware.com Server Side Code

Use any server-side web language (This example code based on WebSmart coding constructs) Get Input parameter from URL string: Searchkey = getparm(“key”);

Code to read 15 records from iSeries Database file Write records Wrthtml(“

etc etc.
Search result 1
” );

Done!

www.bcdsoftware.com Summary

AJAX Is Available Now! AJAX is Easy to Deploy once you have the infrastructure AJAX gives you Client/Server type Web Interaction Without the Distribution Headaches AJAX is Being Actively Researched and Promoted by Major Industry Players Google Microsoft Yahoo! Others

www.bcdsoftware.com Webliography

http://esdi.excelsystems.com/wsexmp/ajaxcst.pgm?w snum=00100 http://www.adaptivepath.com/publications/essays/arc hives/000385.php http://en.wikipedia.org/wiki/AJAX http://developer.apple.com/internet/webcontent/xmlhtt preq.html http://www.clearnova.com/ajax/index.html http://www.ajaxtoolbox.com/ http://www.w3schools.com/dom/dom_http.asp http://www.sitepoint.com/article/remote-scripting-ajax http://webreference.com/programming/javascript/ncz/ http://www.clearnova.com/ajax/ajax_samples.js.txt http://www.xml.com/pub/a/2005/02/09/xml-http- request.html

www.bcdsoftware.com For Detailed Implementation Code

Email me: [email protected] Examples Programs you can run:

http://esdi.excelsystems.com/webtest/ajaxcst.pgm

http://esdi.excelsystems.com/wsexmp/ajaxcst3.pgm?wsnum =00103

http://esdi.excelsystems.com/webapps/ajaxdemo3.pgm Programs written in WebSmart

www.bcdsoftware.com