AJAX Technology Roughly Corresponding to

Page created by Matthew Dunn
 
CONTINUE READING
AJAX Technology Roughly Corresponding to
AJAX Technology
[Roughly Corresponding to Chapter 10]

                                        1
AJAX Technology Roughly Corresponding to
What is AJAX?
• AJAX = Asynchronous JavaScript and XML
  – Allows for asynchronous communication with
    server and partial content retrieval from the
    server and partial update on the client
  – Allows the same good responsiveness
    (promptness) from server as (local) desktop
    applications could

                                                    2
AJAX Technology Roughly Corresponding to
Experiencing “Classic” AJAX Examples
• Google Maps
   – A user can drag the entire map by using the mouse instead of clicking
     on a button or something
   – http://maps.google.com/
• Google Suggest
   – As you type, Google offers suggestions to give you hints and save your
     typing
   – http://www.google.com/webhp?complete=1&hl=en
• Gmail
   – Gmail was a new kind of webmail, built on the idea that email can be
     more intuitive, efficient and useful
   – http://gmail.com/
• Yahoo Maps (new)
   – Now it's even easier and more fun to get where you're going!
   – http://maps.yahoo.com/
                                                                              3
Technical Essence of AJAX?
• Ajax uses existing (special) JavaScript object
  (for HTTP communication) to provide
  asynchronous communication (fast &
  seamless) between client and server which
  enables partial document delivery and
  incremental update (on the client).
   – All these immediately render superb
     responsiveness of a web application from the
    users’ perspective
                                                    4
Traditional
Client/Server
Interactions

Ajax
Client/Server
Interactions
(no waiting!)

                5
Retrospect of Ajax (History)
 ‐ Believed to begin with the iframe element, which appeared in
   IE4 and Netscape 4
    ‐ An iframe element could be made invisible and used to send
   asynchronous requests
 ‐ Microsoft introduced XmlDocument and XMLHTTP ActiveX
   objects in IE5 to support asynchronous requests
    ‐ A similar object is now supported by all other browsers via
   XMLHttpRequest
‐ Two events ignited widespread interest in Ajax:
    1. The advent of Google Map and Google Mail
    2. Jesse James Garrett named the technology as Ajax
                                                                6
Retrospect of Ajax, cont’d
‐ Web applications that benefit the most from Ajax:
  those have frequent interactions between client and
  server, and need to deal with large chunks of data
‐ The goal of Ajax – to provide Web applications with
  great responsiveness comparable to that of (local)
  desk‐top applications
‐ The goal is achieved with two means:
 1. Client’s requests are handled asynchronously  instantly
 2. Only parts of the current document are updated  fast

                                                               7
Retrospect of Ajax, cont’d
‐ Ajax does not introduce/use any new programming
  or markup languages, it just utilizes existing
  tools/technologies creatively and to the fullest:
 ‐ Client side: JavaScript, XML, XHTML, DOM, CSS, XSLT
 ‐ Server side: PHP, servlets, ASP.NET, etc.

                                                         8
AJAX in Action
Sevent Steps to make AJAX work:
1. A client event occurs and triggers the whole process
2. An XMLHttpRequest object is created
3. The XMLHttpRequest object is configured
4. The XMLHttpRequest object makes an asynchronous
   request to Webserver (and designates an callback function)
5. Webserver returns the result typically containing XML
   document (but not necessarily be in XML).
6. The XMLHttpRequest object calls the callback function
   (JavaScript on the client) that processes the result.
7. The HTML DOM (i.e., the current web page) is updated.

                                                                9
An Illustrative Example
• This example helps the user fill a form
  ‐ The form gathers client information
    ‐ asks for the zip code among other things
  ‐ As soon as the zip code is entered, the application sends a request to
   the server, which looks up the city and state and returns them to the
   form
  ‐ Uses JavaScript to put the city and state names in the form
  ‐ PHP is used on the server to look up the city and state
• The html file (of the example)
 ‐ refers to (in its head element) the JavaScript code file
 ‐ registers an event handler on the blur event of the zip code text box

 SHOW popcornA.html (just test it for now, detailed later)
                                                                       10
Structuring of Ajax Asynchronous
             Communication
• Two main functions are used by the application:
   1. The blur event handler
   2. A receiver function (often referred to as a callback
      function) on the client sider, designated to hand the
      server’s response

• Ajax asynchronous communication must also adhere
  to the standard two phases of http communication
  (asynchronous now!)
  1. Request
  2. Response/Receive

                                                              11
The Request Phase (The blur handler)
‐ The asynchronous request must be made through an XMLHttpRequest
   object which is created as follows:
     var xhr = new XMLHttpRequest(); // later referred as the XHR obj.
‐ When the server receives an asynchronous request, it sends back a
  sequence of notices (callbacks), labeled with a ready state, 0, …, 4, of
  which,
    ‐ Only the last callback, with ready state 4, indicates completion of the
      entire response, and requires a corresponding action.
‐ The receiver function (or callback function) must be registered on the
   onreadystatechange property of the XHR object, e.g.,
     xhr.onreadystatechange = receivePlace;

                                                                                12
The Request Phase (continued)
‐ Next, the event handler calls the open method of the XHR object
   with 3 parameters:
   1.   HTTP method, GET or POST, quoted
   2.   The URL of the responsible document/script/program on the server
   3.   A Boolean literal to indicate whether the request is to be asynchronous (true
        by default) or synchronous (false)

   Note: the url param must be attached with form widgets’ values if the GET
   method is used, e.g.,
    xhr.open("GET", "getCityState.php?zip=" + zip, true);

‐ The request is then raised/sent with the send method of XHR
    xhr.send(null);
   //The optional arguments provide the request details (e.g.,
    “n1=v1&n2=v2”); ignored if request method is GET or HEAD.
 SHOW popcornA.js again!

                                                                                   13
The Request Phase (continued)
The Response Document (php on server‐side)
  ‐ Will use a simple hash table of zip codes and names of cities
     and states
  ‐ The response data is then produced with a print
      statement
   SHOW getCityState.php again!

                                                               14
The Receive Phase
‐ The receiver is a JavaScript callback function (no parameters in
   this example)
    ‐ fetch the server response (text),
    ‐ split it into its two parts (city and state),
    ‐ and set the corresponding text boxes to those values
‐ The callback function must be able to access the XHR object
   within its scope!
    ‐ No problem if the object is made global, but could be
   corrupted by simultaneous (asynchronous) requests & responses
    ‐ Best way: register the actual code of the receiver as an
   anonymous func, and make XHR local to the initial event‐handler,
   but “global” to the receiver (callback) func (as in popcornA.js)
                                                               15
The Receive Phase (continued)
‐ Actions of the receiver/callback function:
  1. Put all actions in a condition statement
     to check if response ready state is 4 & request status is 200
      • i.e., response is ready and the is successful (correct)
      • Other states and statuses are just ignored!
  2. Get the response content from the responseText property
  of the XHR object
  3. Split the value into its two parts, city and state
  4. Set the values of the city and state text boxes

SHOW popcornA.js again

                                                                  16
Cross‐Browser Support
‐ What we have done works only with FX2 and IE7 and above,
  but may not with IE5 and IE6
‐ IE5 and IE6 support an ActiveXObject named
  Microsoft.XMLHTTP
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
‐ Generic code that works with “every” browser is:
   if (window.XMLHttpRequest) // IE7, Firefox, Opera, etc.
       xhr= new XMLHttpRequest();
   else // other browsers, e.g., IE5 and IE6
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
- Read more at http://www.w3schools.com/dom/dom_http.asp

                                                             17
Return Document Form: XHTML
In addition to plain TEXT, there are other doc forms.

1. XHTML
 ‐ The most common approach is to place an empty div in the
   original document as a place holder to be directly filled later
   via Ajax asynchronous response.
   ‐ The empty div is filled though its innerHTML property – i.e., to be
  assigned of new content received from asynchronous response, e.g.,
    
                                                                           18
Return Document Form: XHTML (cont’d)
Now, the returned fragment can be inserted in the div with (in callback func)
 var divDom = document.getElementById("replaceable_list");
 divDom.innerHTML = xhr.responseText;
 assuming the following content is in responseText:
     2007 US Champion/Runnerup – football 
     
       New York Giants 
       New England Patriots 
     
  ‐ The disadvantage of using XHTML for the return document is it works well
    only if the markups are complete, correct, and as wanted.

‐ However, oftentimes, it is the pure data that is returned and wanted, in which
   case it must be parsed out of the XHTML; this motivates XML!

                                                                                19
Return Document Form: XML
2. XML
 ‐ For the previous example, the following would be returned:
    2007 US Champion/Runnerup – football 
    New York Giants 
    New England Patriots 

                                                                20
Return Document Form: XML (cont’d)
2. XML (continued)
  ‐ Problem: the XML returned must also be parsed
    ‐ Two common approaches:
      A. Use a DOM bound parsing method
         ‐ Two disadvantages:
           i. Writing the parsing code is tedious
           ii. Support for DOM parsing methods is a bit
               inconsistent over various browsers
       B. Use XSLT style sheets (recommended!)
         ‐ For the same example, (see next slide)

                                                          21
2. XML (continued)
   
                                                         22
Return Document Form: JSON
3. JavaScript Object Notation (JSON)
 - being part of the JavaScript standard, 3rd edition
 - as an added method of representing       objects as strings, using
  two structures in an intermingled way:
  A. Collections of property/value pairs
  B. Arrays of values (may be nested)

                                                                    23
Return Document Form: JSON(cont’d)
3. JavaScript Object Notation (continued), e.g.,
   {"employees" :
     [ {"name" : "Dew, Dawn", "address" : "1222 Wet Lane"},
       {"name" : "Do, Dick", "address" : "332 Doer Road"},
       {"name" : "Deau, Donna", "address" : "222 Donne Street"}
     ]
   }
 This object consists of one property/value pair, whose value is an
  array of three objects, each with two property/value pairs
 ‐ The traditional array and object access conventions are used to
  retrieve the elements, e.g.,
  var address2 = myObj.employees[1].address;
                               // puts "332 Doer Road" in address2
 ‐ JSON objects are returned also via the responseText property
 ‐ But how does one get the object, myObj? (see next slide)
                                                                      24
Return Document Form: JSON(cont’d)
3. JavaScript Object Notation (continued)
   ‐ The object could be obtained by running the eval func on the response
   string
      ‐ This can be dangerous, as the string could have malicious code
   ‐ It is safer to get and use a JSON parser
      var response = xhr.responseText;
      var myObj = JSON.parse(response);
 ‐ JSON has at least three advantages over XML
   1. JSON representations are smaller
   2. This parser is much faster than manual parsing or using XSLT
   3. And much easier than manually parsing or using XSLT
 ‐ However, XML would be better if the returned data is going to be
   integrated with the original document – using XSLT (so it really depends!)

                                                                                25
Return Document Form: JSON(cont’d)
3. JavaScript Object Notation (continued)
    ‐ Example return document:
      {"top_two":
       [
        {"sport": "football", "team": "New York Giants"},
        {"sport": "football", "team": "New England Patriots"},
       ]
     }
   ‐ The following processing puts the data in the HTML document:
    var myObj = JSON.parse(response);
    document.write(" 2007 US Champion/Runnerup“ +
       myObj.top_two[0].sport + "");
    document.write(" " + myObj.top_two[0].team + "");
    document.write("" + myObj.top_two[1].team + "");

                                                                     26
An Example of using POST Method
• Using the POST method in Ajax requires additional work.
  However, the POST method is useful if you must send a large
  chunk of data to the server (packed in request body, instead of
  header).
 …
 xmlHttp.onreadystatechange = responseReceived;
 xmlHttp.open(‘POST', 'example.php', true); // asynchronous request

 var params = “somevar=” + escape(somevalue) + “&othervar=“ + escape(othervalue);

 xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xmlHttp.setRequestHeader("Content-length", params.length);
 xmlHttp.setRequestHeader("Connection", "close");
 xmlHttp.send(params);
 …
 For URL use encodeURL() and decodeURL()
                                                                             27
Blocking Request
• The XML Http Request object can also be used in a blocking
  manner, i.e., for synchronized communication, by passing in
  false to open(..), the request will block on send() until a
  response has been received.
• The blocking will halt the browser and the code while the
  request is waiting for a response. This is usually undesirable
  but
  …
      it may be necessary in certain applications (such as???).
   xmlHttp.open('GET', 'example.php?somevar=somevalue', false);
   xmlHttp.send(null); // this blocks until we receive a response

   // As code is blocked, we can handle the response without an event handler
   alert(‘Response from server: ’ + xhr.responseText);
   // just assume xhr is available in the context of JS code
                                                                       28
Ajax Toolkits: Dojo
There are many toolkits to help build Ajax applications
  on both client and server sides
Dojo – a client‐side toolkit:
   ‐ A free JavaScript library of modules for Ajax and other Web App
   ‐ Provides commonly needed code and hides the differences among
   browsers
   ‐ One particular function, bind, of Dojo creates an XHR object and builds
   an Ajax request
   ‐ To gain access to Dojo module, dojo.js must be included as follows,
Ajax Toolkits (cont’d): Prototype
Prototype – a client‐side extension to JavaScript with tools for Ajax applications
  ‐ Includes a large number of functions and abbreviations of commonly
    needed JavaScript code, e.g.,
    $("name") is an abbreviation for document.getElementById("name")
  ‐ In Prototype, Ajax functionality is encapsulated in the Ajax object
  ‐ A request is created by creating an object of Ajax.Request type:
     ‐ The first parameter of it is the URL of the server
     ‐ The second parameter is a literal object with other required info. :
      ‐ method – "get" or "post"
      ‐ parameters – to attach to the get
      ‐ onSuccess – the anonymous callback function to handle the return
      ‐ onFailure – the anonymous callback function for failure
Refer to textbook or other sources on Internet for more details!
                                                                               30
Security Issues related with Ajax
1. Never put security info in client code, because intruders can
 change the code on the client
2. Ajax applications often have many server‐side programs that
 produce small amounts of data.
 This increases the attack surface of the whole application.
3. Cross‐site scripting – servers provide JavaScript code as an
 Ajax response
  Such code could be modified by intruders before it runs on the client
  Such code must be scanned before it is interpreted
  Intruder code could also come to the client from text boxes used to
 collect return data, e.g., including malicious code

                                                                           31
Ajax Supplements
• Extracted from book “Web Development
  with JavaScript and Ajax Illuminated” by
  Richard Allen, Kai Qian, Lixin Tao, and
  Xiang Fu

                                             32
Limitation of XMLHttpRequest
• Limitation of XMLHttpRequest: you cannot upload a file
  asynchronously (for security reason, you cannot manipulate
  the local file system from Javascript and then upload via XHR
  request);
• The only alternative is to use the standard form action
  (submission) with the help of a hidden frame to upload a
  file/picture (and other data), and yet retain the other parts of
  current web page unaffected ‐‐ the same effect as one
  typically get from Ajax asynchronous communication.
Hidden IFrame
• Actually, long before the broad use of XMLHttpRequest,
  developers were using hidden frames to make requests to
  server without reloading the whole web page being viewed.
• You can hide a frame using CSS and use JavaScript to
  dynamically load content into it and coordinate with other
  elements in the same page without user knowing.
• The  tag specifies an inline frame, and results in
  an embedded window that receives a separate HTML
  document.
•  is often used to embed another document
  within the current HTML document at any location within the
   tags of the main HTML page.
A Motivating Example
• Suppose we want a form for a car sales Web app that
  allows a user to register a car he wants to sell.
• Key feature needed: upload a car’s info with pic
  without reloading the whole page that user is viewing.
   1) A form will allow user to enter info about a car (incl pic)
      and upload, then the app will allow listing of the car so
      that other users can browse.
   2) While the form is submitted, the status indication
      “Uploading …” is shown, resubmission is temporarily
      disabled.
   3) Upon arrival of response from server, it is redirected to the
      iframe, where the onload event handler will take charge
      over, and reset the form (allowing registering another car).
                                                                35
Example Data Flow using a Hidden IFrame
Descriptions of Steps
• The above figure shows how the registration form may look
  and the typical data flow related to the hidden .
• Step 1: the main page sets the IFrame as target to receive
  server’s response (to form’s submission).
• Step 2: form is submitted when user clicks submit button
• Step 3: the Web server responds to the form’s submission and
  the response html doc is redirected to IFrame.
• Step 4: an onload event handler (JavaScript code) registered
  to the IFrame updates the main page – resets the form to be
  ready for registering another car and resets the Iframe’s src to
  initial value.
HTML Code of Main Page

    …
    
      …
      Picture:
      
           Sell my car!
JavaScript Code for Iframe Element
function init() {
    var submitBtn = document.getElementById("submitBtn");
    var origBtnText = submitBtn.firstChild.nodeValue;
    var form = document.getElementById("carEntryForm");
    form.onsubmit = function() {
        submitBtn.disabled = true;
        submitBtn.firstChild.nodeValue =
                "Uploading Information...";
        return true; // form submitted, and return to iframe
    };
    var iframe = document.getElementById("uploadFrame");
    iframe.onload = function() {
        if (iframe.src != "about:blank") {
                   iframe.src != "about:blank“;
            submitBtn.firstChild.nodeValue = origBtnText;
            submitBtn.disabled = false;
        }
        return true;
    };
}
// Execute init() after the page loads.
window.onload = init;
You can do much more …
• You can do much more using a hidden Iframe
  in collaboration with JavaScript code, CSS, and
  form actions!

                                                40
HTTP Streaming
• The standard HTTP model is based on the Web
  browser pulling data from the Web server.
• To achieve a server push model where the server
  pushes data to the browser without client having to
  explictly request it.
• Particularly useful for news and ads and chatting, etc.
Two techniques for HTTP Streaming
• Two techniques, which can be used separately or in
  combination.
• The first tech involves the normal request from the
  browser, followed by multiple responses from the
  server using the same (long‐lived) HTTP connection
   – Technically, server is running a loop: listening for state
     changes and when new data is available, writes to the
     output stream and flushes it, without closing connection.
• This technique is sometimes called page streaming.
Page Streaming Communication
Page Streaming Drawbacks

(1) The browser accumulates objects, which uses up memory
and could eventually cause the interface to bog down;
(2) HTTP connections will inevitably fail, so you must have
some plan to recover;
(3) Most servers aren’t designed to handle multiple
simultaneous long‐lived connections.
Service Streaming
• The second technique, sometimes called service streaming,
  uses one or more long‐lived XMLHttpRequest calls.
• In this technique, you make the long‐lived HTTP connection(s)
  anytime after the page is loaded via subsequent
  XmlHttpRequest objects:
   – Can close and reopen the connection whenever you need.
   – The HTTP connection is kept open and data is pushed to the
     client in the same manner as page streaming.
• An advantage to service streaming, however, is that you can
  push just about any data you want as long as you can process
  it in JavaScript (like JSON).
• With page streaming, you can only push HTML tags as the
  “callback function” is the browser which is supposed to
  accepts only HTML.
Service Streaming Communication
Web Remoting Pitfalls
• The Web has been around long enough that
  users are accustomed to certain conventions.
  – You expect to get a visual progress indicator from
    the browser when waiting for a page to load
  – You expect to be able to click the back button and
    see the last Web page you were viewing
  – You expect to be able to bookmark pages so you
    can return directly to them at a later time
• Beaware that Ajax introduces forms of
  interaction that break these conventions.
You can also read