Slide 1: Asynchronous JavaScript
Rich AJAX Interactions and data inter-change basics
Subramanyan Murali Yahoo! Frontend Engineer, YDN Evangelist
Slide 2: Overview
• • • • • What is Asynchronous ? Applications on Web 2.0 Think Layers Data interchange Why Ajax ? When Ajax ?
Technical Presentation
2
Slide 3: Synchronous Execution
Start-stop-start-stop nature
Slide 4: Synchronous operation
• Start-stop-start-stop nature of interaction • The web by default is Synchronous • Communication between processes is unbuffered, and processes wait until the interaction between them has been completed • Process will wait till conformation to go ahead is got
Technical Presentation
4
Slide 5: Synchronous operation …
Activity Activity Activity
Communication
Communication
System Processing
System Processing
Technical Presentation
5
Slide 6: Synchronous operation …
User Activity User Activity User Activity
Client
Time
Data Transmission
Data Transmission
Server
Data Processing
Data Processing
Technical Presentation
6
Slide 7: Asynchronous Execution
Go with the flow, think about consequences when they arise
Slide 8: Asynchronous operation
• • • • User activity is continuous Operation will not wait for response Chances of Race conditions Good model for GUI applications
– Data Fetch is independent of data render
• Interaction between concepts have to deal with smaller data packets
Technical Presentation
8
Slide 9: Asynchronous operation …
Client
Re Data ques
User Activity
Re Data
nse nse
Data Res po
Ajax
Client Processing
Data Transmission
Client Processing
Data Transmission
Time
Server
System Processing
9
System Processing
Technical Presentation
Data Res po
t ques
t
Slide 10: Asynchronous operation …
• Communication between processes is buffered using buffers of unlimited size • The sender never waits after sending data • Responses needs to be tracked • On the web, if the wait time for response is not handled properly, it might lead to multiple requests by the user
Technical Presentation
10
Slide 11: Rich web applications
Applications on the Web 2.0
Slide 12: Ajax is a broad term
• Any DHTML application is termed as Ajax applications • Is no longer an acronym • Most rich web applications have some sort of asynchronous behavior • Business logic is off loaded to the client • Heavy DOM manipulation
Technical Presentation
12
Slide 13: Caching
• Any repetitive action can be cached
– Style calculation for a DOM element – DOM tree structure – JSON data – Remote response data
• Caching can improve overall user experience • Simple Caching is cheap on the Browser
Technical Presentation
13
Slide 14: Ajax application
Technical Presentation
14
Slide 15: Asynchronous HTTP Request
• XHR for short is an API to transfer data to and fro between the client (User Agent) and the server (Web server) over HTTP
– XHR is an abbreviation for XML Http Request
• The data interchange need not be just XML
– Popular Data interchange formats are JSON, XML, Plain Text and CSV
Technical Presentation
15
Slide 16: Asynchronous HTTP Request …
• Usual steps in Ajax web applications
– Create an XMLHttpRequest object – Make a HTTP request to the server – Register your callback function for handling the response – Handle the response, check for return status – Parse the response on success, display result
Technical Presentation
16
Slide 17: Some code
callBackObj = { success : handleSuccess, failure : handleFailure, argument : [argument1, argument2, argument3], cache : false }; var xhr = YAHOO.util.Connect.asyncRequest("GET", url, callBackObj); if (!xhr) { // User agent does not support XHR } …… function handleSuccess(o) { / * o.tId, o.status, o.getResponseHeader[ ], o.responseText, o.argument */ }
Technical Presentation 17
Slide 18: Scope of execution
• Maintaining scope is very important var callback = { success : handleSuccess, failure : handleFailure, scope : scopeObject }; • Further processing after response needs to happen on the same object that initiated it
Technical Presentation
18
Slide 19: Client side power
• Client machines are powerful • Lot of processing can be done on client
– Sorting tables – Pre-fetching Images – Client side data store
• YUI data source
– Better visualizations
• Vector graphics capabilities
Technical Presentation
19
Slide 20: Application layers
Layer enhancements endlessly
Slide 21: Tier based architecture
• We follow this practice on server side development
– DB layer – Processing Layer – Interface layer
• Core functionality in base layer • Functionality and Style added as layers • Separation of Concern
Slide 22: Tier based architecture …
• CSS for styles / presentation • Javascript validation and DHTML effects
– DHTML widgets to improve usability
• XHR calls to reduce network transfers and improve application responsiveness • Each layer is added unobtrusively
Technical Presentation
22
Slide 23: Why layer
• Programming effort to produce the data is the same, programming effort to format the data varies across formats • Different data formats require different processing capabilities on client and server. • Will make code more extensible for the future
Technical Presentation
23
Slide 24: Data Interchange
Load less, add on later
24 Technical Presentation
Slide 25: Same origin Policy
Cross-domain requests are Denied due to security implications
Slide 26: Data formats
• Web 2.0 popularized the use of JSON as a popular data interchange • XML has been a popular data interchange • Many Web 2.0 applications exchange HTML data which is JSON encoded
– Yahoo! home page
• CSV is also supported by the YUI data source widget
Technical Presentation
26
Slide 27: JSON
“JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss” - Doulas Crockford
Technical Presentation
27
Slide 28: JSON
Lightweight Key value pair based Easy to parse JSON.org provides a json2.js JSON parser for client • All popular languages have JSON parsers • • • •
– All listed in JSON.org
• Interchange is a string
Technical Presentation
28
Slide 29: JSON
var myJSONObject = {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}, {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}, {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"} ] }; myJSONObject.bindings[0].method; // dot notation myJSONObject[“bindings”][0][“method”]; // Array literal notation var myJSONtext = “{‘test’: 5, ‘test2’: 10}”; var myObject = eval('(' + myJSONtext + ')'); // Using json2.js var myObject = JSON.parse (myJSONtext);
Technical Presentation
29
Slide 30: XDR
• Cross Domain Request • XMLHTTPRequest has same origin policy restriction • Future browsers may support an XDR object
– IE and Firefox are close to making a release
Technical Presentation
30
Slide 31: How to do XDR ?
• The most common way is to use a server side proxy
Client calls same origin URI
Remote URL as parameter
Same origin Proxy
Remote URL response
Technical Presentation
31
Slide 32: How to do XDR ? …
• Use a Dynamic script node • This can be used only with services which provide a callback option • Relies on the fact that script node is attached globally and can call a global function • Usually the data passed across in JSON and hence the method is called JSONP response services
– JSON with padding
Technical Presentation
32
Slide 33: Dynamic script node based fetch
{ … scr = document.createElement("script"); scr.type="text/javascript”; scr.id = id; scr.src = “http://xyz.com/query=abc&callback=handleResponse”; … document.body.appendChild(scr); // or can be appended to HEAD } function handleResponse(o) { // o is the data you respond from server }
Technical Presentation
33
Slide 34: XDR data fetch
• YUI get utility provides for this
Technical Presentation
34
Slide 35: Why Ajax ? When Ajax ?
Ajax is an enhancement not a core functionality
35 Technical Presentation
Slide 36: Why?
• Rich User Interface
– User can be more engaged – User need not load the page everytime to get new information
• Snappier Response Time • Lesser content can be loaded the first time • Lower Bandwidth Usage
– No page reloading – Only data specific to user request can be loaded
Slide 37: Do more with less
• Separation of content, formatting and behaviour • Initial load time can come down • Fetch only the data you need, not what your users may need
Technical Presentation
37
Slide 38: Impacts
• Some User Agents may not support Ajax • Search Engine Optimisation gets a hit if not properly designed • Search engines may not be smart enough to navigate the Ajax based pages
– Bad Frontend development can hide the urls of the link that initiate Ajax call – Accessibility of the page can be affected
Technical Presentation
38
Slide 39: Impacts …
• Problem for users that assume GET requests do not change the state of an application
– Confuses Robots, Spiders – Shows Bad Design – Designer does not know the difference between GET & POST requests
• Any client-side changes to the page (using DHTML) are not recorded in the browser's history
– Yahoo! Browser History Manager saves the day !! :-)
Technical Presentation
39
Slide 40: Impacts …
• Back/forward buttons do not work well with rich applications that use DHTML, they need to be controlled by the developer
Technical Presentation
40
Slide 41: Too much richness isn’t good
Always be aware of what your web application can do and what your web application should do
41 Technical Presentation
Slide 42: Always Remember
• Ajax ( in most cases ) has to be used to enhance the page, never use Ajax for a core functionality • Display an indicator/progress of what is happening behind the scenes • Have a timeout for the transaction, do not try to process the request indefinitely • If possible have an option of the user aborting the transaction (equivalent of the "stop" button in the browser)
Technical Presentation
42
Slide 43: Thank you