CMPUT 404

Web Applications and Architecture

Part 08: AJAX

Created by
Abram Hindle (abram.hindle@ualberta.ca)
and Hazel Campbell (hazel.campbell@ualberta.ca).
Copyright 2014-2019.

AJAX

AJAX

What is AJAX?

  • Asynchronous JavaScript and XML
    • Client Side
    • Allows Javascript to make HTTP requests and use the results without redirecting the browser.
    • Enables heavy-clients and lightweight webservices
    • Can be used to avoid presentation responsibility on the webservice.
    • JSON is a common replacement for XML
    • Twitter.com is heavy on Ajax

AJAX Disadvantages

  • You have to manage History, Back button, Bookmarks in JS
  • Security: browsers heavily restrict AJAX to prevent abuse
    • Same-Origin Policy
  • Even more HTTP requests, CPU and RAM

Making Requests

Use JS to make an HTTP request and get the content

Fetch API

Stop trying to make fetch happen! Mean Girls. Paramount Home Entertainment, 2005. Performed by Rachel McAdams.

          
<img height="400" class="centered" id="fetchexample" alt="Stop trying to make fetch happen!"> <cite><em>Mean Girls.</em> Paramount Home Entertainment, 2005. Performed by Rachel McAdams.</cite> <button type="button" onclick="fetchExample()">Fetch!</button>

          
        

Promises, Promises


          
        

Promise dot-chaining


          var request = new Request("images/fetch.gif");
          var promise1 = fetch(request);
          var promise2 = promise1.then(function(response) {
            console.log("Got headers!");
            return response.blob(); // return a promise for raw binary data
          });
          promise2.then(function(blob) {
            console.log("Got data blob!");
            var objectURL = URL.createObjectURL(blob);
            img.src = objectURL;
          });
        }
        

is the same as


          var request = new Request("images/fetch.gif");
          fetch(request).then(function(response) {
            console.log("Got headers!");
            return response.blob(); // return a promise for raw binary data
          }).then(function(blob) {
            console.log("Got data blob!");
            var objectURL = URL.createObjectURL(blob);
            img.src = objectURL;
          });
        

Fetching JSON

Let's make a generic JSON GET function


          
        

Do something with the JSON


          
        

          
          
          

Timers

  • window.setInterval lets you run a function every so many milliseconds.
  • window.setTimeout lets you run a function once after so many milliseconds.

JSON

  • JavaScript Object Notation
  • Strict subset of JavaScript
  • http://json.org/
  • JSON.parse parses JSON text into an Object
  • JSON.stringify turns an Object into JSON text

          
        

Design With AJAX

Design Suggestions:

What are your events?

  • Per user input?
  • Per user commit?
  • Time based?
  • Per Server action?
    • Polling?
  • Data?
  • Content oriented?
  • Messages?
  • Multimedia?
  • Read-based (reddit)

AJAX Observer Pattern

  • Observer pattern is where an observable keeps a collection of observers (listeners) and notifies those observers if anything changed by sending an update message.
  • This works great with AJAX if the observable is held client side in a browser and the observer is client side in the browser! Go ahead!

AJAX Observer Pattern

Observer UML Diagram

AJAX Observer Pattern

  • Still works well with observable in browser and the observers server-side, the client simply notifies via the server's observers whenever an update occurs (but it should also communicate some lightweight state).
  • Due to the lack of a client-side HTTP server it is problematic to do the observer pattern with client side observers.

Observing the Server

  • HTTP is stateless, so a client needs to communicate somehow all of the objects it is observing.
    • Perhaps a serverside Observer proxy that stores observables for a client
  • Clients need to poll the server to check if there are updates. For the observer pattern to work this polling should allow the server to send update commands.
  • Due to bandwidth concerns and latency concerns, an update from the server should probably include relevant data

Observing the Server

  • Fighting against:
    • Latency
    • Bandwidth
    • Lack of communication channels
    • Lack of ability to push messages to a client
    • Polling
    • Timer smashing

Observing the Server

Solutions?

  • Polling: the most common
  • Push API: not supported in all browsers
  • Comet "long polling": difficult server-side support
  • Websockets: need to make a websocket server

Polling the Server

  • Don't send too many requests
  • Batch (bundle together) requests to the server
  • Minimize the number of timers and the frequency of timers
    • E.g. if drawing, a user doesn't need more than 30FPS!
  • Don't make requests until the previous request finished...
  • Don't make requests you don't have to

AJAX Resources

More JavaScript: async and await

  • async functions
    • Return a promise!
  • await in async functions
    • blocks code execution (stop and wait for the promise to resolve)

Async Await Example


          
        

          
          
          

async/await Disadvantages

  • Execution stops at await, instead of continuing in parallel
    • In threads if the browser supports it
  • With .then(...) in a loop, the loop completes instantly and each callback function can run in parallel as soon as its ready
  • With await in a loop, the loop will keep stopping each time it gets to the await

Observer Example

License

Copyright 2014 ⓒ Abram Hindle

Copyright 2019 ⓒ Hazel Victoria Campbell and contributors

Creative Commons Licence
The textual components and original images of this slide deck are placed under the Creative Commons is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Other images used under fair use and copyright their copyright holders.

License

The source code to this slide deck is:

          Copyright (C) 2018 Hakim El Hattab, http://hakim.se, and reveal.js contributors
          Copyright (C) 2019 Hazel Victoria Campbell, Abram Hindle and contributors

          Permission is hereby granted, free of charge, to any person obtaining a copy
          of this software and associated documentation files (the "Software"), to deal
          in the Software without restriction, including without limitation the rights
          to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
          copies of the Software, and to permit persons to whom the Software is
          furnished to do so, subject to the following conditions:

          The above copyright notice and this permission notice shall be included in
          all copies or substantial portions of the Software.

          THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
          IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
          FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
          AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
          LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
          OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN