AJAX

Lecture Notes for CS 142
Spring 2013
John Ousterhout

  • Additional reading for this topic:
    • Pages 195-208 of the online supplement to Dynamic HTML: The Definitive Reference, by Danny Goodman.
    • Note: I do not recommend Chapter 12 of The Rails 3 Way: it fairly confusing and introduces topics such as jQuery and Unobtrusive Javascript that are not relevant for this class.
  • "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;
    }
    
    • Either GET or POST request (but usually POST: can send more data).
    • 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 (for this class, just use raw text).
    • 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.
      • On server, use to_json method, implemented by Rails for all Objects (e.g. models). For example, to convert a collection of models to JSON and return as result of AJAX request:
        @students = Student.find(:all)
        render :text => @students.to_json);
        
        JSON returned in HTTP response:
        [{"advisor_id":"2","birth":"1987-10-22","gpa":3.9,"grad":2009,"id":1,"name":"Anderson"},
         {"advisor_id":"1","birth":"1990-04-16","gpa":3.1,"grad":2012,"id":2,"name":"Jones"},
         {"advisor_id":"1","birth":"1989-08-12","gpa":3.6,"grad":2011,"id":3,"name":"Hernandez"},
         {"advisor_id":"1","birth":"1990-02-04","gpa":3.2,"grad":2011,"id":4,"name":"Chen"}]
        
      • On browser, use eval to generate Javascript object from AJAX response:
        var students = eval(xhr.responseText);
        
      • Browsers optimized to do this quickly.
  • 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.
        <iframe name="xyz"></iframe>
        ...
        <form target="xyz"> ... </form>
        
      • Embed Javascript in the response.
      • This approach offers a better solution to the issue of error handling in forms
        • Target all form POST requests to an invisible <iframe> element.
        • If there are errors, return Javascript that displays error messages in the existing page.
        • This is cleaner and more powerful than the Rails approach of re-rendering the form page.
        • In the normal case where the form post succeeds, redirect as usual (but do it by sending back HTML containing Javascript that redirects the main page)
  • Alternate style of application design (e.g. Gmail): Javascript-only applications
    • 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.
    • node.js: new framework designed for this style of application.