AJAX Patterns



AJAX Patterns

2 2


CMPUT404-AJAX-Slides

AJAX Design Slides

On Github abramhindle / CMPUT404-AJAX-Slides

AJAX Patterns

Created by Abram Hindle abram dot hindle at ualberta dot ca Department of Computing Science University of Alberta Edmonton, Alberta, Canada Earth

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

AJAX

  • Asynchronous JavaScript and XML
    • Client Side
    • Allows Javascript to make HTTP requests and interpret 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 of AJAX ridden websites
    • History and Back button
    • Bookmarks
    • Browser Portability
    • Same origin policy -- Ajax is not cross domain.

AJAX

function getJSON( url, successCallback ) {
   var xhr = new XMLHttpRequest();
   xhr.open('GET', url);
   // This is a call back
   xhr.onreadystatechange = function(){
       // readystate tells you how the transfer is going
       // 4 is done
       if( xhr.readyState === 4 ){
           // This is the HTTP Code
           if(xhr.status === 200){
               successCallback( xhr.responseText );
           } else {
               alert("There was an error " + xhr.status);
           }
       }
   };
   // finally send it
   xhr.send(null);
}

AJAX

Now let's try to do something dynamic! With callbacks

window.setInterval Lets run a function at a set interval.

window.setTimeout Lets you run a function after a period of time.

var myInterval;
function startGetting() {
    myInterval = window.setInterval( function() { //callback
        var now = new Date();
        var s = 1 + (now.getSeconds() % 3);
        var url = s + ".json";
        getJSON( url, function( ourJSON ) { //another
            $("#ajaxy").text( ourJSON );    //callback
        });
    },1000); // 1 second or 1000 ms
}
<div id="ajaxy">AJAXY</div>
Start Getting
AJAXY

AJAX + JSON + JQuery

Now let's try to do something dynamic! With callbacks

window.setInterval Lets run a function at a set interval.

window.setTimeout Lets you run a function after a period of time.

function startGettingJQuery() {
    var myInterval = window.setInterval( function() { //callback
        var now = new Date();
        var s = 1 + (now.getSeconds() % 3);
        var url = s + ".json";
        $.getJSON( url, function( data ) { 
            // JSON Parsing
            $("#ajaxy2").text( data.message ); 
        });
    },1000); // 1 second or 1000 ms
}
<div id="ajaxy2">AJAXY2</div>
Start Getting
AJAXY2

AJAX Design Suggestions

AJAX: 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

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.

AJAX: Observer Pattern with Web Client Observers

  • 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

AJAX: Observer Pattern with Web Client Observers

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

Dealing with Cross Domain Hickups

Timers

  • Don't send too many requests.

  • Bundle up messages to the server if possible.

  • Minimize the number of timers and the frequency of timers.

    • E.g. if drawing a user doesn't need more than 30 frames of second updates.
  • Don't send data if you don't have to!

LICENSE

Copyright 2014 (C) Abram Hindle

The textual components of this slide deck are placed under the Creative Commons Attribute-ShareAlike 4.0 International License (CC BY-SA 4.0)

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

LICENSE

The source code to this slide deck is:

Copyright (C) 2013 Hakim El Hattab, http://hakim.se

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