AJAX Programming Chris Seddon seddon-software@keme.co.uk 2000-12 CRS Enterprises Ltd 1
2000-12 CRS Enterprises Ltd 2
What is Ajax? "Asynchronous JavaScript and XML" Originally described in 2005 by Jesse James Garrett of Adaptive Path Essentially distills existing technologies Asynchronous communication between client and server Partial screen updates Replaces traditional click-wait-redraw model Faster responses Remaining page context available during refresh Updates can be triggered on different events No longer necessary to click on link or button 2000-12 CRS Enterprises Ltd 3
Key Ajax Technologies AJAX is not itself a language! Uses JavaScript on the client and any Language on the Server Client Technologies used: HTML (or (or XHTML) and CSS Presenting Presenting information information Document Object Model Dynamic Dynamic display display and and interaction interaction with with the the information information XMLHttpRequest object Retrieving Retrieving data data ASYNCHRONOUSLY from from the the web web server. server. Javascript Binding Binding everything everything together together 2000-12 CRS Enterprises Ltd 4
Who is using AJAX? Who Isn't? AJAX is now widespread BBC Home page using portals Google Office Applications Creation of thick client look and feel Google Maps Background fetch of map data Flickr Background fetch of photos for display 2000-12 CRS Enterprises Ltd 5
Portals Portals are often built using portlet components Parts of other web sites Users can select from available portlets... and customize their layouts. Multiple views of the same Web application Consider del.icio.us: Browser, JSON, REST/XML, JavaScript Widget interfaces all to the same application. You don t have to go to http://del.icio.us to use it. Simple programming interfaces encourage do it yourself mash-ups JSON, AJAX compatible REST APIs 2000-12 CRS Enterprises Ltd 6
The Ajax Web Application Model Without Ajax User Interface HTTP(S) HTML + CSS Web Server Data Store, Backend processing JavaScript With Ajax User Interface HTML + CSS Ajax Engine HTTP(S) XML / text data Web Server Data Store, Backend processing 2000-12 CRS Enterprises Ltd 7
The Ajax Web Application Model - 2 Client Server data data data data time Client Browser UI input display Ajax Engine Server data data data data time 2000-12 CRS Enterprises Ltd 8
Steps in an Ajax Interaction <script> 2 </script> 1 XMLHttpRequest XMLHttpRequest chris 6 function function callback() callback() {{ // // Update Update HTML HTML DOM DOM // // with with result result }} onkeyup event submit NOT clicked Submit Submit 3 validate?id=chris 5 <response>... </ response > Server-side processing (not (not AJAX AJAX aware) aware) 4 Database 2000-12 CRS Enterprises Ltd 9
Introducing XMLHttpRequest XMLHttpRequest JavaScript object encapsulates making HTTP request from browser to server Scripting HTTP with XMLHttpRequest is a three-part process: 1. 1. Creating an an XMLHttpRequest object 2. 2. Submitting your HTTP request to to a web server 3. 3. Synchronously or or asynchronously retrieving the server s response 2000-12 CRS Enterprises Ltd 10
XMLHttpRequest Methods Methods open(http-method, url, synch-or-asynch) initialisation, with URL, HTTP method to use and synchronous or asynchronous flag setrequestheader(label, value) before sending send(content) make the call, including text or XML content abort( ) abort current call 2000-12 CRS Enterprises Ltd 11
XMLHttpRequest Properties onreadystatechange event handler called whenever readystate changes readystate current status of request status HTTP status responsetext response as text responsexml response as XML statustext status as text 2000-12 CRS Enterprises Ltd 12
XMLHttpRequest Security can only be run on a web page stored on a web server e.g. not your C: drive can only fetch files from the same site that the page is on www.foo.com/a/b/c.html can only fetch from www.foo.com 2000-12 CRS Enterprises Ltd 13
The readystate Property For asynchronous operation Value is integer between 0 and 4 0 not not initialised --open() not not yet yet called 1 initialised but but send() not not called 2 send() called but but no no response from from server 3 data data being received from from server 4 request is is complete Use event handler to be notified of changes to value Some browser inconsistencies with state 3 2000-12 CRS Enterprises Ltd 14
Creating the XMLHttpRequest Object Beware browser incompatibility different object name in IE Use initialisation function to hide differences var varreq; req; function initrequest() {{ if if (( window.xmlhttprequest )){{ req req = new new XMLHttpRequest(); }} else else if if (( window.activexobject )){{ isie isie = true; true; req req = new new ActiveXObject("Microsoft.XMLHTTP"); }} }} // // req reqnow available for for use, use, browsers now now support // // the the same same properties and and methods 2000-12 CRS Enterprises Ltd 15
Preparing and Sending The Request Set event handler <input type="text" size="20" id="userid" name="id" onchange="checkuserid();" /> Initialise XMLHttpRequest object for call function checkuserid( useridelem ) { initrequest(); // from before req.onreadystatechange = handleresponse; if (!target ) { target = document.getelementbyid("userid" ); } var url = "validate?id=" + encode(target.value); req.open( "GET", url, true ); req.send( null ); // Make the call } 2000-12 CRS Enterprises Ltd 16
At The Server (Java Servlets) doget() method checks the userid Sends back appropriate XML with result public public void void doget(httpservletrequest req, req, HttpServletResponse res) res) throws throws IOException, ServletException {{ String String result; result; String StringtargetId = req.getparameter("id"); res.setcontenttype("text/xml"); if if ((targetid!=!= null) null) && &&(isvalidid(targetid))) result result = "<valid>true</valid>"; else else result result = "<valid>false</valid>"; res.getwriter().write(result); }} 2000-12 CRS Enterprises Ltd 17
Processing The Result Callback function registered as onreadystatechange event handler function handleresponse () (){{ if if (( req.readystate == == 4 )){{ // // Request completed if if (( req.status == == 200 200 )){{ // // All All OK OK if if (( req.getresponseheader() == == "text/xml" )){{ // // We We have have XML, XML, retrieve it it as as a DOM DOM document var vardoc = req.responsexml; // // Now Now process the the response }} }} }} }} 2000-12 CRS Enterprises Ltd 18
Using The Result To display a message on the validity of the user id called from response handler, using DOM functions to alter document content function setuidmsg(msg){ var var el el = document.getelementbyid("useridmsg"); var var text text = (msg (msg == == "false") "false")? "Invalid ID" ID" ::"Valid "Valid ID"; ID"; }} var var body body = document.createtextnode(text); if if (el.childnodes[0] )){{ el.replacechild(body, el.childnodes[0]); // // replace replace existing }} else else {{ el.appendchild(body); <body> } } <div } <div id="useridmsg"></div> } </body> 2000-12 CRS Enterprises Ltd 19
Request Timeouts What if the server does not respond? Synchronous requests block entire browser Asynchronous requests can be timed out Use Window.setTimeout() with XMLHttpRequest.abort() If response arrives before timeout, use Window.clearTimeout() 2000-12 CRS Enterprises Ltd 20
Response Encodings - XML For structured data, XML is often used // // Server Server side side code, code, generating response resp.setcontenttype("text/xml"); resp.setheader("cache-control", "no-cache"); resp.getwriter().write("<book> <author>john Doe</author> <title>all About About Ajax</title> </book>"); if if (( req.getresponseheader() == == "text/xml" )){{ // // We We have have XML, XML, retrieve it it as as a DOM DOM document var var doc doc = req.responsexml; // // Now Now pull pull out out data data using using JavaScript DOM DOM functions var var author author = doc.childnodes[0].text }} 2000-12 CRS Enterprises Ltd 21
Response Encodings - JSON... JavaScript Object Notation (JSON) easy to convert to JavaScript object use eval or a parser (for more security) // // Server Server side side code, code, generating response resp.setcontenttype("text/javascript"); resp.setheader("cache-control", "no-cache"); resp.getwriter().write("[ "author": "John "John Doe", Doe", "title": "title":"all "All About About Ajax" Ajax" ]]"); "); [[ "author": "John "John Doe", Doe", "title": "title":"all "All About About Ajax" Ajax" ]] 2000-12 CRS Enterprises Ltd 22
... JSON Can make cross-domain requests unlike AJAX which uses XMLHttpRequest yo make cross-domain requests, just dynamically create your <script> tags using the DOM and add a src attribute to point to the desired JSON URL CSS can also be expressed in JSON JavaScript's eval() method to convert the string into a real JavaScript object var data = eval('(' + req.responsetext + ')'); 2000-12 CRS Enterprises Ltd 23
JavaScript/AJAX Toolkits 2000-12 CRS Enterprises Ltd 24
JavaScript/AJAX/JSON Toolkits jquery http://jquery.com GWT (Google Web Toolkit) http://code.google.com/webtoolkit Dojo http://www.dojotoolkit.org YUI (Yahoo! User Interface Library) http://developer.yahoo.com/yui DWR http://getahead.org/dwr script.aculo.us http://script.aculo.us Prototype http://www.prototypejs.org 2000-12 CRS Enterprises Ltd 25
Other Tools Firefox Extensions Firebug view the XMLHttpRequests Selenium Record scripts and replay them! JSView See All JavaScript/CSS with a click Modify Headers (what the name implies!) NoScript Turn off or limit scripts Fiddler and other Proxys watch all client-server traffic 2000-12 CRS Enterprises Ltd 26
jquery jquery wrapper wraps a set of DOM elements jquery is also an object <html> <html> <head> <script <script type="text/javascript" src="jquery.js"></script> <script <script type="text/javascript"> $(document).ready(function() {{ $("h1").css("color", "blue"); }) }) </script> need to know the CSS </head> selector syntax <body> <h1>test Page</h1> </body> </html> 2000-12 CRS Enterprises Ltd 27
GWT (Google Web Toolkit) Open source Java software development framework Develop Web applications as if they were Swing-like GUIs Easier AJAX application development You write your front end in Java using any Java IDE available (e.g. Eclipse, JProfiler, JUnit, IntelliJ ) GWT complier will automatically convert it into browser-complaint JavaScript and HTML Confirm that the Web App. Runs successfully in each browser GWT Architecture GWT Java-to-JavaScript Compiler: Java-to-JavaScript compiler GWT Hosted Web Browser: run and execute your GWT applications JRE emulation library: contains JavaScript implementations of the most widely used classes in the Java standard class library. GWT Web UI class library: set of custom interfaces and classes that let your create web browser "widgets with use of CSS 2000-12 CRS Enterprises Ltd 28
Dojo Dojo is an open-source JavaScript toolkit Widely used Large range of functionality Basic layout Fonts, images etc Animations Ajax Supports all major browsers Preferred toolkit in Fidelity http://www.dojotoolkit.org 2000-12 CRS Enterprises Ltd 29
Dojo - Getting Started Basic capabilities implemented in file dojo.js Dojo provides hook to ensure that document is completely loaded before functionality is applied Hides cross-browser differences <html> <html> <head> <title>dojo Toolkit Toolkit Test Test Page</title> <!-- <!--load the the dojo dojo toolkit toolkit base base --> --> <script <script type="text/javascript" src="js/dojo/dojo.js" djconfig="parseonload:true, isdebug:false"></script> <script <script type="text/javascript"> var var init init = function() {{ alert("page is is ready..."); }; }; dojo.addonload(init); </script> </head>...... 2000-12 CRS Enterprises Ltd 30
YUI (Yahoo! User Interface Library) Collection of JavaScript and CSS resources Makes RIA (Rich Internet Applications) easier to build Open source Yahoo! User Interface Library components Utilities UI Controls CSS resources Yahoo! Design Patterns Library easily implement design patterns 2000-12 CRS Enterprises Ltd 31
DWR (Direct Web Remoting) Java open source library facilitates writing AJAX web sites Two components: Java Servlet running on the server to process requests and sends responses back to the browser. JavaScript running in the browser to send requests and can dynamically update the webpage. Dynamically generates JavaScript feels like the execution is happening in the browser, but... server is executing the code DWR converts data back and forth using a callback function 2000-12 CRS Enterprises Ltd 32