SlideShare une entreprise Scribd logo
1  sur  43
Asynchronous JavaScript
Rich AJAX Interactions and data inter-change basics




                                                     Subramanyan Murali
                                                                  Yahoo!
                                        Frontend Engineer, YDN Evangelist
Overview
•    What is Asynchronous ?
•    Applications on Web 2.0
•    Think Layers
•    Data interchange
•    Why Ajax ? When Ajax ?




Technical Presentation    2
Synchronous Execution
   Start-stop-start-stop nature
Synchronous operation
•  Start-stop-start-stop nature of interaction
•  The web by default is Synchronous
•  Communication between processes is un-
   buffered, and processes wait until the
   interaction between them has been completed
•  Process will wait till conformation to go ahead is
   got




Technical Presentation    4
Synchronous operation …

     Activity                            Activity                       Activity




                         Communication               Communication




                     System Processing              System Processing




Technical Presentation                       5
Synchronous operation …

  User Activity                            User Activity                       User Activity



Client



Time                Data Transmission                      Data Transmission




                         Data Processing                   Data Processing
Server


Technical Presentation                            6
Asynchronous Execution
Go with the flow, think about consequences when
                      they arise
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
Asynchronous operation …

Client                                        User Activity




                                                              Data




                                                                                                  nse
                                                  nse
              Data




                                                                                                     po
                                                     po




                                                                   Re
                   Re




                                                                                                 Res
                                                 Res




                                                                 ques
                 ques




Ajax




                                                                                            Data
                                            Data




                                                                      t
                   t




                          Client                                            Client
                        Processing                                        Processing


Time                    Data Transmission                               Data Transmission




Server                  System Processing                               System Processing


Technical Presentation                                    9
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
Rich web applications
  Applications on the Web 2.0
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
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
Ajax application




Technical Presentation   14
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
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
Some code
callBackObj = {
        success : handleSuccess,
        failure  : handleFailure,
        argument : [argument1, argument2, argument3],
        cache     : false
  };

  var xhr = YAHOO.util.Connect.asyncRequest(quot;GETquot;, 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
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
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
Application layers
Layer enhancements endlessly
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
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
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
Data Interchange
                          Load less, add on later




 24
Technical Presentation
Same origin Policy




Cross-domain requests are Denied
    due to security implications
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
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
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
JSON

var myJSONObject = {quot;bindingsquot;: [
     {quot;ircEventquot;: quot;PRIVMSGquot;, quot;methodquot;: quot;newURIquot;, quot;regexquot;: quot;^http://.*quot;},
     {quot;ircEventquot;: quot;PRIVMSGquot;, quot;methodquot;: quot;deleteURIquot;, quot;regexquot;: quot;^delete.*quot;},
     {quot;ircEventquot;: quot;PRIVMSGquot;, quot;methodquot;: quot;randomURIquot;, quot;regexquot;: quot;^random.*quot;}
   ]
};

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
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
How to do XDR ?
•  The most common way is to use a server side
   proxy


           Client calls same    Remote URL as 
               origin URI         parameter 




                                 Same origin     Remote URL 
                                   Proxy          response 




Technical Presentation                      31
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
Dynamic script node based fetch

{
…
scr = document.createElement(quot;scriptquot;);
scr.type=quot;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
XDR data fetch
•  YUI get utility provides for this




Technical Presentation     34
Why Ajax ? When Ajax ?
     Ajax is an enhancement not a core functionality




 35
Technical Presentation
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
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
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
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
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
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
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 quot;stopquot; button
   in the browser)



Technical Presentation   42
Thank you

Contenu connexe

Similaire à Asynchronous Javascript and Rich Internet Aplications

Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
rsnarayanan
 
iPhone Development For Experienced Web Developers
iPhone Development For Experienced Web DevelopersiPhone Development For Experienced Web Developers
iPhone Development For Experienced Web Developers
lisab517
 
Practical Thin Server Architecture With Dojo Peter Svensson
Practical Thin Server Architecture With Dojo Peter SvenssonPractical Thin Server Architecture With Dojo Peter Svensson
Practical Thin Server Architecture With Dojo Peter Svensson
rajivmordani
 
My Presentation On Ajax
My Presentation On AjaxMy Presentation On Ajax
My Presentation On Ajax
Ghaffar Khan
 
Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2
guest66dc5f
 
Applications of the REST Principle
Applications of the REST PrincipleApplications of the REST Principle
Applications of the REST Principle
elliando dias
 
Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008
codebits
 

Similaire à Asynchronous Javascript and Rich Internet Aplications (20)

Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
 
Web 2.0 & Ajax Basics
Web 2.0 & Ajax BasicsWeb 2.0 & Ajax Basics
Web 2.0 & Ajax Basics
 
Comet from JavaOne 2008
Comet from JavaOne 2008Comet from JavaOne 2008
Comet from JavaOne 2008
 
iPhone Development For Experienced Web Developers
iPhone Development For Experienced Web DevelopersiPhone Development For Experienced Web Developers
iPhone Development For Experienced Web Developers
 
Client-Server-Kommunikation mit dem Command Pattern
Client-Server-Kommunikation mit dem Command PatternClient-Server-Kommunikation mit dem Command Pattern
Client-Server-Kommunikation mit dem Command Pattern
 
Galaxy
GalaxyGalaxy
Galaxy
 
Practical Thin Server Architecture With Dojo Peter Svensson
Practical Thin Server Architecture With Dojo Peter SvenssonPractical Thin Server Architecture With Dojo Peter Svensson
Practical Thin Server Architecture With Dojo Peter Svensson
 
Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQueryDrupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery
 
20080611accel
20080611accel20080611accel
20080611accel
 
Application Architecture Trends
Application Architecture TrendsApplication Architecture Trends
Application Architecture Trends
 
Petabytes of Data and No Servers: Corteva Scales DNA Analysis to Meet Increas...
Petabytes of Data and No Servers: Corteva Scales DNA Analysis to Meet Increas...Petabytes of Data and No Servers: Corteva Scales DNA Analysis to Meet Increas...
Petabytes of Data and No Servers: Corteva Scales DNA Analysis to Meet Increas...
 
Seminar - JBoss Migration
Seminar - JBoss MigrationSeminar - JBoss Migration
Seminar - JBoss Migration
 
My Presentation On Ajax
My Presentation On AjaxMy Presentation On Ajax
My Presentation On Ajax
 
Deploying and Scaling using AWS
Deploying and Scaling using AWSDeploying and Scaling using AWS
Deploying and Scaling using AWS
 
Qcon
QconQcon
Qcon
 
Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2Shreeraj-Hacking_Web_2
Shreeraj-Hacking_Web_2
 
Applications of the REST Principle
Applications of the REST PrincipleApplications of the REST Principle
Applications of the REST Principle
 
Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008
 
Ajax World Fall08
Ajax World Fall08Ajax World Fall08
Ajax World Fall08
 
Scaling a Rails Application from the Bottom Up
Scaling a Rails Application from the Bottom Up Scaling a Rails Application from the Bottom Up
Scaling a Rails Application from the Bottom Up
 

Plus de Subramanyan Murali

Location aware Web Applications
Location aware Web ApplicationsLocation aware Web Applications
Location aware Web Applications
Subramanyan Murali
 

Plus de Subramanyan Murali (18)

Yahoo Mail moving to React
Yahoo Mail moving to ReactYahoo Mail moving to React
Yahoo Mail moving to React
 
Clipboard support on Y! mail
Clipboard support on Y! mailClipboard support on Y! mail
Clipboard support on Y! mail
 
What the Hack??
What the Hack??What the Hack??
What the Hack??
 
Web as a data resource
Web as a data resourceWeb as a data resource
Web as a data resource
 
Is it good to be paranoid ?
Is it good to be paranoid ?Is it good to be paranoid ?
Is it good to be paranoid ?
 
When Why What of WWW
When Why What of WWWWhen Why What of WWW
When Why What of WWW
 
Welcome to University Hack Day @ IIT Chennai
Welcome to University Hack Day @ IIT Chennai Welcome to University Hack Day @ IIT Chennai
Welcome to University Hack Day @ IIT Chennai
 
YUI for your Hacks
YUI for your Hacks YUI for your Hacks
YUI for your Hacks
 
YUI open for all !
YUI open for all !YUI open for all !
YUI open for all !
 
Fixing the developer Mindset
Fixing the developer MindsetFixing the developer Mindset
Fixing the developer Mindset
 
Get me my data !
Get me my data !Get me my data !
Get me my data !
 
Professional Css
Professional CssProfessional Css
Professional Css
 
Basics of Rich Internet Applications
Basics of Rich Internet ApplicationsBasics of Rich Internet Applications
Basics of Rich Internet Applications
 
Yahoo! Frontend Building Blocks
Yahoo! Frontend Building BlocksYahoo! Frontend Building Blocks
Yahoo! Frontend Building Blocks
 
Location aware Web Applications
Location aware Web ApplicationsLocation aware Web Applications
Location aware Web Applications
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
YUI for your Hacks-IITB
YUI for your Hacks-IITBYUI for your Hacks-IITB
YUI for your Hacks-IITB
 
Yahoo! Geo Technologies-IITD
Yahoo! Geo Technologies-IITDYahoo! Geo Technologies-IITD
Yahoo! Geo Technologies-IITD
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Asynchronous Javascript and Rich Internet Aplications

  • 1. Asynchronous JavaScript Rich AJAX Interactions and data inter-change basics Subramanyan Murali Yahoo! Frontend Engineer, YDN Evangelist
  • 2. Overview •  What is Asynchronous ? •  Applications on Web 2.0 •  Think Layers •  Data interchange •  Why Ajax ? When Ajax ? Technical Presentation 2
  • 3. Synchronous Execution Start-stop-start-stop nature
  • 4. Synchronous operation •  Start-stop-start-stop nature of interaction •  The web by default is Synchronous •  Communication between processes is un- buffered, and processes wait until the interaction between them has been completed •  Process will wait till conformation to go ahead is got Technical Presentation 4
  • 5. Synchronous operation … Activity Activity Activity Communication Communication System Processing System Processing Technical Presentation 5
  • 6. Synchronous operation … User Activity User Activity User Activity Client Time Data Transmission Data Transmission Data Processing Data Processing Server Technical Presentation 6
  • 7. Asynchronous Execution Go with the flow, think about consequences when they arise
  • 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
  • 9. Asynchronous operation … Client User Activity Data nse nse Data po po Re Re Res Res ques ques Ajax Data Data t t Client Client Processing Processing Time Data Transmission Data Transmission Server System Processing System Processing Technical Presentation 9
  • 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
  • 11. Rich web applications Applications on the Web 2.0
  • 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
  • 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
  • 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
  • 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
  • 17. Some code callBackObj = { success : handleSuccess, failure : handleFailure, argument : [argument1, argument2, argument3], cache : false }; var xhr = YAHOO.util.Connect.asyncRequest(quot;GETquot;, 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 24. Data Interchange Load less, add on later 24 Technical Presentation
  • 25. Same origin Policy Cross-domain requests are Denied due to security implications
  • 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
  • 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
  • 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
  • 29. JSON var myJSONObject = {quot;bindingsquot;: [ {quot;ircEventquot;: quot;PRIVMSGquot;, quot;methodquot;: quot;newURIquot;, quot;regexquot;: quot;^http://.*quot;}, {quot;ircEventquot;: quot;PRIVMSGquot;, quot;methodquot;: quot;deleteURIquot;, quot;regexquot;: quot;^delete.*quot;}, {quot;ircEventquot;: quot;PRIVMSGquot;, quot;methodquot;: quot;randomURIquot;, quot;regexquot;: quot;^random.*quot;} ] }; 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
  • 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
  • 31. How to do XDR ? •  The most common way is to use a server side proxy Client calls same  Remote URL as  origin URI  parameter  Same origin  Remote URL  Proxy  response  Technical Presentation 31
  • 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
  • 33. Dynamic script node based fetch { … scr = document.createElement(quot;scriptquot;); scr.type=quot;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
  • 34. XDR data fetch •  YUI get utility provides for this Technical Presentation 34
  • 35. Why Ajax ? When Ajax ? Ajax is an enhancement not a core functionality 35 Technical Presentation
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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 quot;stopquot; button in the browser) Technical Presentation 42