SlideShare ist ein Scribd-Unternehmen logo
1 von 67
Downloaden Sie, um offline zu lesen
Introduction to Ajax

Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com
Agenda
1.What is Rich User Experience?
2.Rich Internet Application (RIA) Technologies
3.AJAX: Real-life examples & Usage cases
4.What is and Why AJAX?
5.Technologies used in AJAX
6.Anatomy of AJAX operation
7.XMLHttpRequest Methods & Properties
8.DOM APIs & InnerHTML
9.AJAX Security
10.JavaScript debugging tools
                                                 2
Topics Covered in Other Presentations
• AJAX Toolkits & Frameworks
• JSON (JavaScript Object Notation)
• Dojo Toolkit
• DWR (Direct Web Remoting)
• AJAX-enabled JSF Components
• Google Web Toolkit (GWT)
• jMaki
• Phobos (MVC-based server-side scripting)
• Ajax and Portlet/Portal
• Wicket and Shale (as AJAX-aware Web applicaion
  frameworks)
• JavaScript Programming Best Practices            3
1. Rich User Experience
   for Web Application
Rich User Experience
• Take a look at a typical desktop application
  (Spreadsheet app, etc.)
• The program responses intuitively and quickly
• The program gives a user meaningful feedback's
  instantly
  > A cell in a spreadsheet changes color when you hover your
    mouse over it
  > Icons light up as mouse hovers them
• Things happen naturally
  > No need to click a button or a link to trigger an event
                                                                5
Characteristics of Conventional Web
Applications (Apps without Ajax)

• “Click, wait, and refresh” user interaction
  > Any communication with the server forces a page refresh
• Synchronous “request/response” communication
  model
  > The user has to wait for the response
• Page-driven: Workflow is based on pages
  > Page-navigation logic is determined by the server



                                                              6
Issues of Conventional Web Application
• Interruption of user operation
  > Users cannot perform any operation while waiting for a response
• Loss of operational context during refresh
  > Loss of information on the screen
  > Loss of scrolled position
• No instant feedback's to user activities
  > A user has to wait for the next page
• Constrained by HTML
  > Lack of useful widgets


These are the reasons why Rich Internet Application (RIA)
  technologies were born.                               7
2. Rich Internet
Application (RIA)
  Technologies
Rich Internet Application (RIA)
Technologies
•   Applet
•   Macromedia Flash/Air
•   Java WebStart
•   DHTML
•   DHTML with Hidden IFrame
•   Ajax
•   Sliverlight (Windows only)
•   JavaFX (Java Platform)
                                  9
Applet
• Pros:
  > Can use full Java APIs
  > Custom data streaming, graphic manipulation, threading, and
    advanced GUIs
  > Well-established scheme
• Cons:
  > Code downloading time could be significant
  > Reliability concern - a mal-functioning applet can crash a
    browser
• There is renewed interest in applet, however, as a
  RIA technology with Java SE 10 Update 10
  > Solves old applet problems
                                                                 10
Macromedia Flash
• Designed for playing interactive movies originally
• Programmed with ActionScript
• Implementation examples
  > Macromedia Flex
  > Laszlo suite (open source)
• Pros:
  > Good for displaying vector graphics
• Cons:
  > Browser needs a Flash plug-in
  > ActionScript is proprietary
                                                       11
Java WebStart
• Desktop application delivered over the net
  > Leverages the strengths of desktop apps and applet
• Pros
  >   Desktop experience once loaded
  >   Leverages Java technology to its fullest extent
  >   Disconnected operation is possible
  >   Application can be digitally signed
  >   Incremental redeployment
• Cons
  > Old JRE-based system do not work
  > First-time download time could be still significant
                                                          12
DHTML (Dynamic HTML)
• DHTML = JavaScript + DOM + CSS
• Used for creating interactive applications
• No asynchronous communication, however
  > Full page refresh still required
  > Reason why it has only a limited success




                                               13
DHTML with Hidden IFrame

• IFrame was introduced as a programmable layout to
  a web page
  > An IFrame is represented as an element of a DOM tree
  > You can move it, resize it, even hide it while the page is
     visible
• An hidden IFrame can add asynchronous behavior
  > The visible user experience is uninterrupted – operational
     context is not lost
• It is still a hack

                                                                 14
AJAX
• DHTML plus Asynchronous communication
  capability through XMLHttpRequest
• Pros
  >   Emerges as a viable RIA technology
  >   Good industry momentum
  >   Several toolkits and frameworks are emerging
  >   No need to download code & no plug-in required
• Cons
  > Still some browser incompatibility
  > JavaScript is hard to maintain and debug
• AJAX-enabled JSF components will help
                                                       15
3. AJAX:
Real-life Examples &
Usecases
Real-Life Examples of AJAX Apps
• Google maps
  > http://maps.google.com/
• Goolgle Suggest
  > http://www.google.com/webhp?complete=1&hl=en
• NetFlix
  > http://www.netflix.com/BrowseSelection?lnkctr=nmhbs
• Gmail
  > http://gmail.com/
• Yahoo Maps (new)
  > http://maps.yahoo.com/
• Many more are popping everywhere                        17
AJAX: Demo
Google Maps,
Yahoo Maps New
Key Aspects of Google Maps

• A user can drag the entire map by using the mouse
  > Instead of clicking on a button or something
  > The action that triggers the download of new map data is not
    a specific click on a link but a moving the map around with a
    mouse
• Behind the scene - AJAX is used
  > The map data is requested and downloaded asynchronously
    in the background
• Other parts of the page remains the same
  > No loss of operational context

                                                                    19
Usage cases for AJAX
• Real-time server-side input form data validation
  > User IDs, serial numbers, postal codes
  > Removes the need to have validation logic at both client side
    for user responsiveness and at server side for security and
    other reasons
• Auto-completion
  > Email address, name, or city name may be auto-completed as
    the user types
• Master detail operation
  > Based on a user selection, more detailed information can be
    fetched and displayed
                                                                    20
Usage cases for AJAX
• Advanced GUI widgets and controls
  > Controls such as tree controls, menus, and progress bars
    may be provided that do not require page refreshes
• Refreshing data
  > HTML pages may poll data from a server for up-to-date data
    such as scores, stock quotes, weather, or application-specific
    data




                                                                 21
Demo: AJAX Sample Apps

javapassion.com/handsonlab
s/ajaxbasics2/#Exercise_1
Demo Scenario

• Run sample AJAX applications within NetBeans IDE
  > Auto completion
  > Data validation
  > Progress bar
• You can try this demo yourself
  > These applications are provided as part of the hands-on lab.
  > www.javapassion.com/handsonlabs/4257_ajaxbasics2.zip




                                                                   23
4. AJAX:
What is and Why AJAX?
Why AJAX?
• Intuitive and natural user interaction
  > No clicking required
  > Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and
  refresh" user interaction model
  > Only user interface elements that contain new information are
    updated asynchronously (no interruption to user operation)
  > The rest of the user interface remains displayed without
    interruption (no loss of operational context)
• Data-driven (as opposed to page-driven)
  > UI is handled in the client while the server provides data
                                                                 25
Why AJAX?
• Asynchronous communication replaces
  "synchronous request/response model."
  > A user can continue to use the application while the client
    program requests information from the server in the
    background
  > Separation of displaying from data fetching




                                                                  26
Interrupted user
operation while
the data is being
fetched




Uninterrupted
user operation
while data is
being fetched


                 27
28
5. AJAX:
Technologies Used
in AJAX
Technologies Used In AJAX
• Javascript
  > Loosely typed scripting language
  > JavaScript function is called when an event in a page occurs
  > Glue for the whole AJAX operation
• DOM
  > Represents the structure of XML and HTML documents
  > API for accessing and manipulating structured documents
• CSS
  > Allows for a clear separation of the presentation style from the
    content and may be changed programmatically by JavaScript
• XMLHttpRequest
  > JavaScript object that performs asynchronous interaction with the
    server                                                              30
XMLHttpRequest
• JavaScript object
• Adopted by modern browsers
  > Mozilla™, Firefox, Safari, and Opera
• Communicates with a server via standard HTTP
  GET/POST
• XMLHttpRequest object works in the background for
  performing asynchronous communication with the
  backend server
  > Does not interrupt user operation

                                                  31
Server-Side AJAX Request
Processing
• Server programming model remains the same
  > It receives standard HTTP GETs/POSTs
  > Can use Servlet, JSP, JSF, whatever web technologies...
• With minor caveats
  > Could have more frequent and finer-grained requests from
    clients (design issue)
  > Response content type can be
     > text/xml
     > text/plain
     > text/json
     > text/javascript
                                                               32
6. AJAX: Anatomy Of
AJAX Interaction
using “Data Validation”
Sample Application
Anatomy of an AJAX Interaction
(Data Validation Example)




                                 34
Steps of AJAX Operation
1.A client event occurs
2.An XMLHttpRequest object is created
3.The XMLHttpRequest object is configured
4.The XMLHttpRequest object makes an async. request
5.The ValidateServlet returns an XML document
  containing the result
6.The XMLHttpRequest object calls the callback() function
  and processes the result
7.The HTML DOM is updated
                                                       35
1. A Client event occurs
• A JavaScript function is called as the result of an
  event
• Example: validateUserId() JavaScript function is
  mapped as a event handler to a onkeyup event on
  input form field whose id is set to “userid”

  <input type="text"
          size="20"
           id="userid"
          name="id"
       onkeyup="validateUserId();">
                                                        36
2. An XMLHttpRequest object is
created
var req;
function initRequest() {
   if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
       isIE = true;
       req = new ActiveXObject("Microsoft.XMLHTTP");
   }
}
function validateUserId() {
   initRequest();
   req.onreadystatechange = processRequest;
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   req.open("GET", url, true);
   req.send(null);
}                                                             37
3. An XMLHttpRequest object is
configured with a callback function
var req;
function initRequest() {
   if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
       isIE = true;
       req = new ActiveXObject("Microsoft.XMLHTTP");
   }
}
function validateUserId() {
   initRequest();
   req.onreadystatechange = processRequest; // callback function
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   req.open("GET", url, true);
   req.send(null);
}                                                                  38
4. XMLHttpRequest object makes an async.
request
function initRequest() {
   if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
       isIE = true;
       req = new ActiveXObject("Microsoft.XMLHTTP");
   }
}
function validateUserId() {
   initRequest();
   req.onreadystatechange = processRequest;
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   req.open("GET", url, true);
   req.send(null);
}
• URL is set to validate?id=greg                              39
5. The ValidateServlet returns an XML
document containing the results (Server)

 public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
  String targetId = request.getParameter("id");
  if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
         response.setContentType("text/xml");
         response.setHeader("Cache-Control", "no-cache");
         response.getWriter().write("<valid>true</valid>");
      } else {
         response.setContentType("text/xml");
         response.setHeader("Cache-Control", "no-cache");
         response.getWriter().write("<valid>false</valid>");
      }
  }
                                                                               40
6. XMLHttpRequest object calls callback()
function and processes the result
• The XMLHttpRequest object was configured to call
  the processRequest() function when there is a state
  change to the readyState of the XMLHttpRequest
  object

  function processRequest() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var message = ...;

  ...
                                                        41
7. The HTML DOM is updated
• JavaScript technology gets a reference to any
  element in a page using DOM API
• The recommended way to gain a reference to an
  element is to call
  > document.getElementById("userIdMessage"), where
    "userIdMessage" is the ID attribute of an element appearing in
    the HTML document
• JavaScript technology may now be used to modify
  the element's attributes; modify the element's style
  properties; or add, remove, or modify child elements
                                                                42
1. <script type="text/javascript">
2. function setMessageUsingDOM(message) {
3.    var userMessageElement = document.getElementById("userIdMessage");
4.    var messageText;
5.    if (message == "false") {
6.        userMessageElement.style.color = "red";
7.        messageText = "Invalid User Id";
8.    } else {
9.        userMessageElement.style.color = "green";
10.       messageText = "Valid User Id";
11. }
12. var messageBody = document.createTextNode(messageText);
13. // if the messageBody element has been created simple replace it otherwise
14. // append the new element
15. if (userMessageElement.childNodes[0]) {
16.       userMessageElement.replaceChild(messageBody,
17.                                         userMessageElement.childNodes[0]);
18. } else {
19.       userMessageElement.appendChild(messageBody);
20. }
21.}
22.</script>
23.<body>
24. <div id="userIdMessage"></div>
25.</body>                                                                       43
7. AJAX:
XMLHttpRequest
Methods & Properties
XMLHttpRequest Methods
• open(“HTTP method”, “URL”, syn/asyn)
  > Assigns HTTP method, destination URL, mode
• send(content)
  > Sends request including string or DOM object data
• abort()
  > Terminates current request
• getAllResponseHeaders()
  > Returns headers (labels + values) as a string
• getResponseHeader(“header”)
  > Returns value of a given header
• setRequestHeader(“label”,”value”)
  > Sets Request Headers before sending
                                                        45
XMLHttpRequest Properties
• onreadystatechange
  > Set with an JavaScript event handler that fires at each state
    change
• readyState – current status of request
  > 0 = uninitialized
  > 1 = loading
  > 2 = loaded
  > 3 = interactive (some data has been returned)
  > 4 = complete
• status
  > HTTP Status returned from server: 200 = OK

                                                                    46
XMLHttpRequest Properties
• responseText
  > String version of data returned from the server
• responseXML
  > XML document of data returned from the server
• statusText
  > Status text returned from server




                                                      47
8. AJAX: DOM API &
InnerHTML
Browser and DOM
• Browsers maintain an object representation of the
  documents being displayed
  > In the form of Document Object Model (DOM)
  > It is readily available as document JavaScript object
• APIs are available that allow JavaScript code to
  modify the DOM programmatically




                                                            49
DOM APIs vs. innerHTML
• DOM APIs provide a means for JavaScript code to
  navigate/modify the content in a page
  function setMessageUsingDOM(message) {
          var userMessageElement = document.getElementById("userIdMessage");
          var messageText;
          if (message == "false") {
              userMessageElement.style.color = "red";
              messageText = "Invalid User Id";
          } else {
              userMessageElement.style.color = "green";
              messageText = "Valid User Id";
          }
         var messageBody = document.createTextNode(messageText);
          if (userMessageElement.childNodes[0]) {
              userMessageElement.replaceChild(messageBody,
                 userMessageElement.childNodes[0]);
          } else {
              userMessageElement.appendChild(messageBody);
          }
  }
                                                                               50
DOM APIs vs. innerHTML
• Using innerHTML is easier: Sets or retrieves the HTML
  between the start and end tags of the object
  function setMessageUsingDOM(message) {
          var userMessageElement = document.getElementById("userIdMessage");
          var messageText;
          if (message == "false") {
              userMessageElement.style.color = "red";
              messageText = "Invalid User Id";
          } else {
              userMessageElement.style.color = "green";
              messageText = "Valid User Id";
          }
         userMessageElement.innerHTML = messageText;
  }




                                                                               51
Do I Have To Use
XmlHttpRequest to
Write Ajax application?
Ajax Frameworks and Toolkits
• In general, you are going to use Ajax frameworks
  and toolkits
• These toolkits provide higher-level API, which hides
  the complexity of XmlHttpRequest




                                                         53
9. AJAX Security
AJAX Security: Server Side
• AJAX-based Web applications use the same server-
  side security schemes of regular Web applications
  > You specify authentication, authorization, and data protection
    requirements in your web.xml file (declarative) or in your
    program (programatic)
• AJAX-based Web applications are subject to the
  same security threats as regular Web applications
  > Cross-site scripting
  > Injection flaw


                                                                 55
AJAX Security: Client Side
• JavaScript code is visible to a user/hacker
  > Hacker can use the JavaScript code for inferring server side
    weaknesses
  > Obfustication or compression can be used
• JavaScript code is downloaded from the server and
  executed (“eval”) at the client
  > Can compromise the client by mal-intended code
• Downloaded JavaScript code is constrained by
  sand-box security model
  > Can be relaxed for signed JavaScript
                                                                   56
Recommendations from OWASP
•   Use .innerText instead of .innerHtml
•   Don't use eval
•   Encode data before its use
•   Avoid serialization
•   Avoid building XML dynamically




                                           57
10. JavaScript Development
Tools (Try these tools with
“AJAX Basics & Dev.
Tools” Hands-on Lab)
Development Tools for NetBeans IDE

• Building AJAX Applications over NetBeans is not that
  much different from building regular Web applications
• NetBeans supports JavaScript editor and debugger




                                                          59
Development Tools on Mozilla
Browser
• Mozilla FireBug debugger (add-on)
    > This is the most comprehensive and most useful JavaScript
      debugger
    > This tool does things all other tools do and more
•   Mozilla JavaScript console
•   Mozilla DOM inspector (comes with Firefox package)
•   Mozilla Venkman JavaScript debugger (add-on)
•   Mozilla LiveHTTPHeaders HTTP monitor (similar to
    NetBeans HTTP monitor)

                                                                  60
Mozilla FireBug Debugger
• Spy on XMLHttpRequest traffic
• JavaScript debugger for stepping through code one line at
  a time
• Inspect HTML source, computed style, events, layout and
  the DOM
• Status bar icon shows you when there is an error in a web
  page
• A console that shows errors from JavaScript and CSS
• Log messages from JavaScript in your web page to the
  console (bye bye "alert debugging")
• An JavaScript command line (no more "javascript:" in the
  URL bar)
                                                              61
11. AJAX:
Current Issues & Futures
Current Issues of AJAX
• Complexity is increased
  > Server side developers will need to understand that
    presentation logic will be required in the HTML client pages as
    well as in the server-side logic
  > Page developers must have JavaScript technology skills
• AJAX-based applications can be difficult
  to debug, test, and maintain
  > JavaScript is hard to test - automatic testing is hard
  > Weak modularity in JavaScript - namespace collision possible
  > Lack of design patterns or best practice guidelines yet
• Toolkits/Frameworks still maturing
                                                                  63
Current Issues of AJAX
• No standardization of the XMLHttpRequest yet
  > Future version of IE will address this
• No support of XMLHttpRequest in old browsers
  > Iframe will help
• JavaScript technology dependency & incompatibility
  > Must be enabled for applications to function
  > Still some browser incompatibilities
• JavaScript code is visible to a hacker
  > Poorly designed JavaScript code can invite security problem



                                                                  64
Browsers Which Support
XMLHttpRequest
•   Mozilla Firefox 1.0 and above
•   Netscape version 7.1 and above
•   Apple Safari 1.2 and above.
•   Microsoft Internet Exporer 5 and above
•   Konqueror
•   Opera 7.6 and above


                                             65
AJAX Futures
•   AJAX-enabled JSF Component libraries
•   Standardization of XMLHttpRequest
•   Better browser support
•   Better and Standardized Framework support
•   More best practice guidelines in the programming
    model



                                                       66
AJAX Basics
Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com

Weitere ähnliche Inhalte

Was ist angesagt?

Ajax Introduction Presentation
Ajax   Introduction   PresentationAjax   Introduction   Presentation
Ajax Introduction Presentationthinkphp
 
Intoduction to Ajax
Intoduction to AjaxIntoduction to Ajax
Intoduction to AjaxRISHAV ANURAG
 
Ajax and ASP.NET AJAX
Ajax and ASP.NET AJAXAjax and ASP.NET AJAX
Ajax and ASP.NET AJAXJulie Iskander
 
Web 2.0 & Ajax Basics
Web 2.0 & Ajax BasicsWeb 2.0 & Ajax Basics
Web 2.0 & Ajax BasicsAbhishek Nagar
 
Ajax & ASP.NET 2
Ajax & ASP.NET 2Ajax & ASP.NET 2
Ajax & ASP.NET 2Talal Alsubaie
 
Ajax for Libraries
Ajax for LibrariesAjax for Libraries
Ajax for Librariesguest5aa3e8
 
jQuery and AJAX with Rails
jQuery and AJAX with RailsjQuery and AJAX with Rails
jQuery and AJAX with RailsAlan Hecht
 
Beyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 AppsBeyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 AppsMarcos Caceres
 
Ajax Using JSP with prototype.js
Ajax Using JSP with prototype.jsAjax Using JSP with prototype.js
Ajax Using JSP with prototype.jsTushar Chauhan
 
4005-713 ` XML Architecture, Tools & Technique ` Presentation
4005-713 ` XML Architecture, Tools & Technique ` Presentation4005-713 ` XML Architecture, Tools & Technique ` Presentation
4005-713 ` XML Architecture, Tools & Technique ` Presentationlitcigar
 

Was ist angesagt? (20)

Ajax
AjaxAjax
Ajax
 
Ajax Introduction Presentation
Ajax   Introduction   PresentationAjax   Introduction   Presentation
Ajax Introduction Presentation
 
Ajax PPT
Ajax PPTAjax PPT
Ajax PPT
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
AJAX
AJAXAJAX
AJAX
 
Intoduction to Ajax
Intoduction to AjaxIntoduction to Ajax
Intoduction to Ajax
 
Webdevelopment
WebdevelopmentWebdevelopment
Webdevelopment
 
Ajax and ASP.NET AJAX
Ajax and ASP.NET AJAXAjax and ASP.NET AJAX
Ajax and ASP.NET AJAX
 
Web 2.0 & Ajax Basics
Web 2.0 & Ajax BasicsWeb 2.0 & Ajax Basics
Web 2.0 & Ajax Basics
 
Ajax & ASP.NET 2
Ajax & ASP.NET 2Ajax & ASP.NET 2
Ajax & ASP.NET 2
 
Ajax and RJS
Ajax and RJSAjax and RJS
Ajax and RJS
 
Ajax for Libraries
Ajax for LibrariesAjax for Libraries
Ajax for Libraries
 
Sohamsg ajax
Sohamsg ajaxSohamsg ajax
Sohamsg ajax
 
jQuery and AJAX with Rails
jQuery and AJAX with RailsjQuery and AJAX with Rails
jQuery and AJAX with Rails
 
Beyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 AppsBeyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 Apps
 
Ajax
AjaxAjax
Ajax
 
Ajax Using JSP with prototype.js
Ajax Using JSP with prototype.jsAjax Using JSP with prototype.js
Ajax Using JSP with prototype.js
 
4005-713 ` XML Architecture, Tools & Technique ` Presentation
4005-713 ` XML Architecture, Tools & Technique ` Presentation4005-713 ` XML Architecture, Tools & Technique ` Presentation
4005-713 ` XML Architecture, Tools & Technique ` Presentation
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 

Ähnlich wie Introduction to Ajax: Key Concepts and Real-World Examples

Ajax & Reverse Ajax Presenation
Ajax & Reverse Ajax PresenationAjax & Reverse Ajax Presenation
Ajax & Reverse Ajax PresenationRishabh Garg
 
AJAX Introduction [Autosaved].pptx
AJAX Introduction [Autosaved].pptxAJAX Introduction [Autosaved].pptx
AJAX Introduction [Autosaved].pptxJobin86
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Jeremy Likness
 
Progressive Web Apps and React
Progressive Web Apps and ReactProgressive Web Apps and React
Progressive Web Apps and ReactMike Melusky
 
Web applications
Web applicationsWeb applications
Web applicationsPeter Berezny
 
The Mobile Web - HTML5 on mobile devices
The Mobile Web - HTML5 on mobile devicesThe Mobile Web - HTML5 on mobile devices
The Mobile Web - HTML5 on mobile devicesWesley Hales
 
Transforming the web into a real application platform
Transforming the web into a real application platformTransforming the web into a real application platform
Transforming the web into a real application platformMohanadarshan Vivekanandalingam
 
Asynchronous javascript and xml
Asynchronous javascript and xmlAsynchronous javascript and xml
Asynchronous javascript and xmlBui Kiet
 
Mobile Ajax Workshop
Mobile Ajax WorkshopMobile Ajax Workshop
Mobile Ajax WorkshopBryan Rieger
 
Ajax
AjaxAjax
AjaxTech_MX
 
SynapseIndia asp.net2.0 ajax Development
SynapseIndia asp.net2.0 ajax DevelopmentSynapseIndia asp.net2.0 ajax Development
SynapseIndia asp.net2.0 ajax DevelopmentSynapseindiappsdevelopment
 
Cloud Computing in Systems Programming Curriculum
Cloud Computing in Systems Programming CurriculumCloud Computing in Systems Programming Curriculum
Cloud Computing in Systems Programming CurriculumSteven Miller
 
Javascript & Jquery
Javascript & JqueryJavascript & Jquery
Javascript & JqueryGurpreet singh
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentationBharat_Kumawat
 
Developing Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax PushDeveloping Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax PushDoris Chen
 

Ähnlich wie Introduction to Ajax: Key Concepts and Real-World Examples (20)

Ajax & Reverse Ajax Presenation
Ajax & Reverse Ajax PresenationAjax & Reverse Ajax Presenation
Ajax & Reverse Ajax Presenation
 
Mobile Web
Mobile WebMobile Web
Mobile Web
 
AJAX Introduction [Autosaved].pptx
AJAX Introduction [Autosaved].pptxAJAX Introduction [Autosaved].pptx
AJAX Introduction [Autosaved].pptx
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!
 
Ajax
AjaxAjax
Ajax
 
Progressive Web Apps and React
Progressive Web Apps and ReactProgressive Web Apps and React
Progressive Web Apps and React
 
Ajax
AjaxAjax
Ajax
 
Web applications
Web applicationsWeb applications
Web applications
 
The Mobile Web - HTML5 on mobile devices
The Mobile Web - HTML5 on mobile devicesThe Mobile Web - HTML5 on mobile devices
The Mobile Web - HTML5 on mobile devices
 
ITI006En-AJAX
ITI006En-AJAXITI006En-AJAX
ITI006En-AJAX
 
Transforming the web into a real application platform
Transforming the web into a real application platformTransforming the web into a real application platform
Transforming the web into a real application platform
 
Asynchronous javascript and xml
Asynchronous javascript and xmlAsynchronous javascript and xml
Asynchronous javascript and xml
 
Mobile Ajax Workshop
Mobile Ajax WorkshopMobile Ajax Workshop
Mobile Ajax Workshop
 
Ajax
AjaxAjax
Ajax
 
SynapseIndia asp.net2.0 ajax Development
SynapseIndia asp.net2.0 ajax DevelopmentSynapseIndia asp.net2.0 ajax Development
SynapseIndia asp.net2.0 ajax Development
 
Cloud Computing in Systems Programming Curriculum
Cloud Computing in Systems Programming CurriculumCloud Computing in Systems Programming Curriculum
Cloud Computing in Systems Programming Curriculum
 
Grails and Ajax
Grails and AjaxGrails and Ajax
Grails and Ajax
 
Javascript & Jquery
Javascript & JqueryJavascript & Jquery
Javascript & Jquery
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
Developing Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax PushDeveloping Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax Push
 

KĂźrzlich hochgeladen

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

KĂźrzlich hochgeladen (20)

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 

Introduction to Ajax: Key Concepts and Real-World Examples

  • 1. Introduction to Ajax Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com
  • 2. Agenda 1.What is Rich User Experience? 2.Rich Internet Application (RIA) Technologies 3.AJAX: Real-life examples & Usage cases 4.What is and Why AJAX? 5.Technologies used in AJAX 6.Anatomy of AJAX operation 7.XMLHttpRequest Methods & Properties 8.DOM APIs & InnerHTML 9.AJAX Security 10.JavaScript debugging tools 2
  • 3. Topics Covered in Other Presentations • AJAX Toolkits & Frameworks • JSON (JavaScript Object Notation) • Dojo Toolkit • DWR (Direct Web Remoting) • AJAX-enabled JSF Components • Google Web Toolkit (GWT) • jMaki • Phobos (MVC-based server-side scripting) • Ajax and Portlet/Portal • Wicket and Shale (as AJAX-aware Web applicaion frameworks) • JavaScript Programming Best Practices 3
  • 4. 1. Rich User Experience for Web Application
  • 5. Rich User Experience • Take a look at a typical desktop application (Spreadsheet app, etc.) • The program responses intuitively and quickly • The program gives a user meaningful feedback's instantly > A cell in a spreadsheet changes color when you hover your mouse over it > Icons light up as mouse hovers them • Things happen naturally > No need to click a button or a link to trigger an event 5
  • 6. Characteristics of Conventional Web Applications (Apps without Ajax) • “Click, wait, and refresh” user interaction > Any communication with the server forces a page refresh • Synchronous “request/response” communication model > The user has to wait for the response • Page-driven: Workflow is based on pages > Page-navigation logic is determined by the server 6
  • 7. Issues of Conventional Web Application • Interruption of user operation > Users cannot perform any operation while waiting for a response • Loss of operational context during refresh > Loss of information on the screen > Loss of scrolled position • No instant feedback's to user activities > A user has to wait for the next page • Constrained by HTML > Lack of useful widgets These are the reasons why Rich Internet Application (RIA) technologies were born. 7
  • 8. 2. Rich Internet Application (RIA) Technologies
  • 9. Rich Internet Application (RIA) Technologies • Applet • Macromedia Flash/Air • Java WebStart • DHTML • DHTML with Hidden IFrame • Ajax • Sliverlight (Windows only) • JavaFX (Java Platform) 9
  • 10. Applet • Pros: > Can use full Java APIs > Custom data streaming, graphic manipulation, threading, and advanced GUIs > Well-established scheme • Cons: > Code downloading time could be significant > Reliability concern - a mal-functioning applet can crash a browser • There is renewed interest in applet, however, as a RIA technology with Java SE 10 Update 10 > Solves old applet problems 10
  • 11. Macromedia Flash • Designed for playing interactive movies originally • Programmed with ActionScript • Implementation examples > Macromedia Flex > Laszlo suite (open source) • Pros: > Good for displaying vector graphics • Cons: > Browser needs a Flash plug-in > ActionScript is proprietary 11
  • 12. Java WebStart • Desktop application delivered over the net > Leverages the strengths of desktop apps and applet • Pros > Desktop experience once loaded > Leverages Java technology to its fullest extent > Disconnected operation is possible > Application can be digitally signed > Incremental redeployment • Cons > Old JRE-based system do not work > First-time download time could be still significant 12
  • 13. DHTML (Dynamic HTML) • DHTML = JavaScript + DOM + CSS • Used for creating interactive applications • No asynchronous communication, however > Full page refresh still required > Reason why it has only a limited success 13
  • 14. DHTML with Hidden IFrame • IFrame was introduced as a programmable layout to a web page > An IFrame is represented as an element of a DOM tree > You can move it, resize it, even hide it while the page is visible • An hidden IFrame can add asynchronous behavior > The visible user experience is uninterrupted – operational context is not lost • It is still a hack 14
  • 15. AJAX • DHTML plus Asynchronous communication capability through XMLHttpRequest • Pros > Emerges as a viable RIA technology > Good industry momentum > Several toolkits and frameworks are emerging > No need to download code & no plug-in required • Cons > Still some browser incompatibility > JavaScript is hard to maintain and debug • AJAX-enabled JSF components will help 15
  • 17. Real-Life Examples of AJAX Apps • Google maps > http://maps.google.com/ • Goolgle Suggest > http://www.google.com/webhp?complete=1&hl=en • NetFlix > http://www.netflix.com/BrowseSelection?lnkctr=nmhbs • Gmail > http://gmail.com/ • Yahoo Maps (new) > http://maps.yahoo.com/ • Many more are popping everywhere 17
  • 19. Key Aspects of Google Maps • A user can drag the entire map by using the mouse > Instead of clicking on a button or something > The action that triggers the download of new map data is not a specific click on a link but a moving the map around with a mouse • Behind the scene - AJAX is used > The map data is requested and downloaded asynchronously in the background • Other parts of the page remains the same > No loss of operational context 19
  • 20. Usage cases for AJAX • Real-time server-side input form data validation > User IDs, serial numbers, postal codes > Removes the need to have validation logic at both client side for user responsiveness and at server side for security and other reasons • Auto-completion > Email address, name, or city name may be auto-completed as the user types • Master detail operation > Based on a user selection, more detailed information can be fetched and displayed 20
  • 21. Usage cases for AJAX • Advanced GUI widgets and controls > Controls such as tree controls, menus, and progress bars may be provided that do not require page refreshes • Refreshing data > HTML pages may poll data from a server for up-to-date data such as scores, stock quotes, weather, or application-specific data 21
  • 22. Demo: AJAX Sample Apps javapassion.com/handsonlab s/ajaxbasics2/#Exercise_1
  • 23. Demo Scenario • Run sample AJAX applications within NetBeans IDE > Auto completion > Data validation > Progress bar • You can try this demo yourself > These applications are provided as part of the hands-on lab. > www.javapassion.com/handsonlabs/4257_ajaxbasics2.zip 23
  • 24. 4. AJAX: What is and Why AJAX?
  • 25. Why AJAX? • Intuitive and natural user interaction > No clicking required > Mouse movement is a sufficient event trigger • "Partial screen update" replaces the "click, wait, and refresh" user interaction model > Only user interface elements that contain new information are updated asynchronously (no interruption to user operation) > The rest of the user interface remains displayed without interruption (no loss of operational context) • Data-driven (as opposed to page-driven) > UI is handled in the client while the server provides data 25
  • 26. Why AJAX? • Asynchronous communication replaces "synchronous request/response model." > A user can continue to use the application while the client program requests information from the server in the background > Separation of displaying from data fetching 26
  • 27. Interrupted user operation while the data is being fetched Uninterrupted user operation while data is being fetched 27
  • 28. 28
  • 30. Technologies Used In AJAX • Javascript > Loosely typed scripting language > JavaScript function is called when an event in a page occurs > Glue for the whole AJAX operation • DOM > Represents the structure of XML and HTML documents > API for accessing and manipulating structured documents • CSS > Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript • XMLHttpRequest > JavaScript object that performs asynchronous interaction with the server 30
  • 31. XMLHttpRequest • JavaScript object • Adopted by modern browsers > Mozilla™, Firefox, Safari, and Opera • Communicates with a server via standard HTTP GET/POST • XMLHttpRequest object works in the background for performing asynchronous communication with the backend server > Does not interrupt user operation 31
  • 32. Server-Side AJAX Request Processing • Server programming model remains the same > It receives standard HTTP GETs/POSTs > Can use Servlet, JSP, JSF, whatever web technologies... • With minor caveats > Could have more frequent and finer-grained requests from clients (design issue) > Response content type can be > text/xml > text/plain > text/json > text/javascript 32
  • 33. 6. AJAX: Anatomy Of AJAX Interaction using “Data Validation” Sample Application
  • 34. Anatomy of an AJAX Interaction (Data Validation Example) 34
  • 35. Steps of AJAX Operation 1.A client event occurs 2.An XMLHttpRequest object is created 3.The XMLHttpRequest object is configured 4.The XMLHttpRequest object makes an async. request 5.The ValidateServlet returns an XML document containing the result 6.The XMLHttpRequest object calls the callback() function and processes the result 7.The HTML DOM is updated 35
  • 36. 1. A Client event occurs • A JavaScript function is called as the result of an event • Example: validateUserId() JavaScript function is mapped as a event handler to a onkeyup event on input form field whose id is set to “userid” <input type="text" size="20" id="userid" name="id" onkeyup="validateUserId();"> 36
  • 37. 2. An XMLHttpRequest object is created var req; function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); } } function validateUserId() { initRequest(); req.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); req.open("GET", url, true); req.send(null); } 37
  • 38. 3. An XMLHttpRequest object is configured with a callback function var req; function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); } } function validateUserId() { initRequest(); req.onreadystatechange = processRequest; // callback function if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); req.open("GET", url, true); req.send(null); } 38
  • 39. 4. XMLHttpRequest object makes an async. request function initRequest() { if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true; req = new ActiveXObject("Microsoft.XMLHTTP"); } } function validateUserId() { initRequest(); req.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); req.open("GET", url, true); req.send(null); } • URL is set to validate?id=greg 39
  • 40. 5. The ValidateServlet returns an XML document containing the results (Server) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter("id"); if ((targetId != null) && !accounts.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>true</valid>"); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>false</valid>"); } } 40
  • 41. 6. XMLHttpRequest object calls callback() function and processes the result • The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object function processRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = ...; ... 41
  • 42. 7. The HTML DOM is updated • JavaScript technology gets a reference to any element in a page using DOM API • The recommended way to gain a reference to an element is to call > document.getElementById("userIdMessage"), where "userIdMessage" is the ID attribute of an element appearing in the HTML document • JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements 42
  • 43. 1. <script type="text/javascript"> 2. function setMessageUsingDOM(message) { 3. var userMessageElement = document.getElementById("userIdMessage"); 4. var messageText; 5. if (message == "false") { 6. userMessageElement.style.color = "red"; 7. messageText = "Invalid User Id"; 8. } else { 9. userMessageElement.style.color = "green"; 10. messageText = "Valid User Id"; 11. } 12. var messageBody = document.createTextNode(messageText); 13. // if the messageBody element has been created simple replace it otherwise 14. // append the new element 15. if (userMessageElement.childNodes[0]) { 16. userMessageElement.replaceChild(messageBody, 17. userMessageElement.childNodes[0]); 18. } else { 19. userMessageElement.appendChild(messageBody); 20. } 21.} 22.</script> 23.<body> 24. <div id="userIdMessage"></div> 25.</body> 43
  • 45. XMLHttpRequest Methods • open(“HTTP method”, “URL”, syn/asyn) > Assigns HTTP method, destination URL, mode • send(content) > Sends request including string or DOM object data • abort() > Terminates current request • getAllResponseHeaders() > Returns headers (labels + values) as a string • getResponseHeader(“header”) > Returns value of a given header • setRequestHeader(“label”,”value”) > Sets Request Headers before sending 45
  • 46. XMLHttpRequest Properties • onreadystatechange > Set with an JavaScript event handler that fires at each state change • readyState – current status of request > 0 = uninitialized > 1 = loading > 2 = loaded > 3 = interactive (some data has been returned) > 4 = complete • status > HTTP Status returned from server: 200 = OK 46
  • 47. XMLHttpRequest Properties • responseText > String version of data returned from the server • responseXML > XML document of data returned from the server • statusText > Status text returned from server 47
  • 48. 8. AJAX: DOM API & InnerHTML
  • 49. Browser and DOM • Browsers maintain an object representation of the documents being displayed > In the form of Document Object Model (DOM) > It is readily available as document JavaScript object • APIs are available that allow JavaScript code to modify the DOM programmatically 49
  • 50. DOM APIs vs. innerHTML • DOM APIs provide a means for JavaScript code to navigate/modify the content in a page function setMessageUsingDOM(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "false") { userMessageElement.style.color = "red"; messageText = "Invalid User Id"; } else { userMessageElement.style.color = "green"; messageText = "Valid User Id"; } var messageBody = document.createTextNode(messageText); if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } 50
  • 51. DOM APIs vs. innerHTML • Using innerHTML is easier: Sets or retrieves the HTML between the start and end tags of the object function setMessageUsingDOM(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "false") { userMessageElement.style.color = "red"; messageText = "Invalid User Id"; } else { userMessageElement.style.color = "green"; messageText = "Valid User Id"; } userMessageElement.innerHTML = messageText; } 51
  • 52. Do I Have To Use XmlHttpRequest to Write Ajax application?
  • 53. Ajax Frameworks and Toolkits • In general, you are going to use Ajax frameworks and toolkits • These toolkits provide higher-level API, which hides the complexity of XmlHttpRequest 53
  • 55. AJAX Security: Server Side • AJAX-based Web applications use the same server- side security schemes of regular Web applications > You specify authentication, authorization, and data protection requirements in your web.xml file (declarative) or in your program (programatic) • AJAX-based Web applications are subject to the same security threats as regular Web applications > Cross-site scripting > Injection flaw 55
  • 56. AJAX Security: Client Side • JavaScript code is visible to a user/hacker > Hacker can use the JavaScript code for inferring server side weaknesses > Obfustication or compression can be used • JavaScript code is downloaded from the server and executed (“eval”) at the client > Can compromise the client by mal-intended code • Downloaded JavaScript code is constrained by sand-box security model > Can be relaxed for signed JavaScript 56
  • 57. Recommendations from OWASP • Use .innerText instead of .innerHtml • Don't use eval • Encode data before its use • Avoid serialization • Avoid building XML dynamically 57
  • 58. 10. JavaScript Development Tools (Try these tools with “AJAX Basics & Dev. Tools” Hands-on Lab)
  • 59. Development Tools for NetBeans IDE • Building AJAX Applications over NetBeans is not that much different from building regular Web applications • NetBeans supports JavaScript editor and debugger 59
  • 60. Development Tools on Mozilla Browser • Mozilla FireBug debugger (add-on) > This is the most comprehensive and most useful JavaScript debugger > This tool does things all other tools do and more • Mozilla JavaScript console • Mozilla DOM inspector (comes with Firefox package) • Mozilla Venkman JavaScript debugger (add-on) • Mozilla LiveHTTPHeaders HTTP monitor (similar to NetBeans HTTP monitor) 60
  • 61. Mozilla FireBug Debugger • Spy on XMLHttpRequest traffic • JavaScript debugger for stepping through code one line at a time • Inspect HTML source, computed style, events, layout and the DOM • Status bar icon shows you when there is an error in a web page • A console that shows errors from JavaScript and CSS • Log messages from JavaScript in your web page to the console (bye bye "alert debugging") • An JavaScript command line (no more "javascript:" in the URL bar) 61
  • 63. Current Issues of AJAX • Complexity is increased > Server side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic > Page developers must have JavaScript technology skills • AJAX-based applications can be difficult to debug, test, and maintain > JavaScript is hard to test - automatic testing is hard > Weak modularity in JavaScript - namespace collision possible > Lack of design patterns or best practice guidelines yet • Toolkits/Frameworks still maturing 63
  • 64. Current Issues of AJAX • No standardization of the XMLHttpRequest yet > Future version of IE will address this • No support of XMLHttpRequest in old browsers > Iframe will help • JavaScript technology dependency & incompatibility > Must be enabled for applications to function > Still some browser incompatibilities • JavaScript code is visible to a hacker > Poorly designed JavaScript code can invite security problem 64
  • 65. Browsers Which Support XMLHttpRequest • Mozilla Firefox 1.0 and above • Netscape version 7.1 and above • Apple Safari 1.2 and above. • Microsoft Internet Exporer 5 and above • Konqueror • Opera 7.6 and above 65
  • 66. AJAX Futures • AJAX-enabled JSF Component libraries • Standardization of XMLHttpRequest • Better browser support • Better and Standardized Framework support • More best practice guidelines in the programming model 66
  • 67. AJAX Basics Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com