AJAX

Lecture Notes for CS 142
Fall 2010
John Ousterhout

  • Readings for this topic:
    • Pages 195-208 of the online supplement to Dynamic HTML: The Definitive Reference, by Danny Goodman.
    • Section 24.1 of Agile Web Development with Rails.
  • "Asynchronous Javascript And XML"
  • Simple idea:
    • Issue an HTTP request to the server from Javascript without replacing the current page.
    • Process the response with Javascript code in the browser.
  • Example:
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = xhrHandler;
    xhr.open("POST", url);
    xhr.send(postData);
    ...
    function xhrHandler() {
      if (this.readyState != 4) {
          return;
      }
      if (this.status != 200) {
          // Handle error ...
          return;
      }
      ...
      var text = this.responseText;
      var document = this.responseXML;
    }
    
    • Either GET or POST request (but usually POST).
    • Arbitrary request message (typically name-value pairs just like other POSTs).
    • Event-based: sending code returns immediately after calling send.
    • Event handler gets called at various stages in the processing of the request (usually only care about state 4: done).
    • Response available as either raw text or an XML document.
    • Can set request headers and read response headers.
  • For complete details on XMLHttpRequest objects, see the W3C specification: W3C Documentation for XMLHttpRequest.
  • AJAX responses tend to be one of the following:
    • HTML to replace the contents of an element.
    • Javascript code to execute.
    • Structured data to be processed by Javascript in the browser:
      • Original design was for this to be XML, but XML not used much for this anymore:
        • Other forms simpler.
        • Slow parsing in the browser.
        • Quirky XML parsers (especially Internet Explorer).
      • Most common form today: JSON (JavaScript Object Notation): Javascript string that evaluates to an Object:
        {name: "Alice", gpa: 3.5,
        friends: ["Bill", "Carol", "David"]}
        
      • Used to transport data between server and browser.
      • Evaluated on browser to generate Javascript data.
      • Browsers optimized to do this quickly.
  • Rails example of higher-level abstraction built on AJAX:
    <%= observe_field
        :form_userName,
        :update       => "completionMenu",
        :url          => {:action => "nameChoices"} %>
    
    • Helper method for generating HTML.
    • Detects changes in the form field whose DOM id is form_userName.
    • Makes an AJAX request to the nameChoices action in the current controller.
    • Response is HTML, which will replace the innerHTML of the DOM element whose id is completionMenu.
  • Other ways to get AJAX-like behavior:
    • Use Javascript to add a new <script> DOM element:
      • Fetches Javascript and executes it.
      • Can provide parameters in the URL.
      • Can embed data in the response using JSON.
    • Form posts:
      • Use the target attribute to redirect the POST response to a hidden iframe.
      • Embed Javascript in the response.
  • Alternate style of application design (e.g. Gmail):
    • HTML rendering done on the browser rather than the server.
    • Main page for application consists mostly of Javascript.
    • Javascript code uses AJAX to fetch raw data from server, not HTML.
    • Javascript code then renders HTML, adds to DOM.