AJAX, JSON, and XML

Connecting Web Applications

Randy J. Fortier
randy.fortier@uoit.ca
@randy_fortier

Outline

  • What is AJAX?
  • How does AJAX work?
  • How can I write AJAX code?
  • JSON
    • Processing JSON
  • XML
    • Processing XML
  • Open data

AJAX, JSON, and XML

AJAX

AJAX

  • Asynchronous JavaScript and XMLHttpRequest:
    • The aim is to increase the interactivity of a website
    • When you work with a web page, the web page itself can be interacting with the server, but without reloading the (whole) page you are viewing
    • The result is an uninterrupted user experience, with full server-side capabilities

AJAX

  • Synchronous
    • The browser waits for the response
    • Once received, the browser re-renders the page
  • Asynchronous
    • The browser sends the request in the background
    • The page continues to be responsive
    • Once the response is received, JavaScript code may modify the page

When to Use AJAX

  • Login (e.g. login before you can comment)
  • Chat (e.g. Facebook chat)
  • Ratings, reviews for products
  • Advertisements and dynamic content (e.g. scores, prices)
  • Filtering/sorting result tables

Basic Process

  • An event (e.g. button press) occurs
  • The JavaScript handler for that event:
    • Creates an XMLHttpRequest object
    • Specifies the URL, method, callback function
  • The callback function:
    • Collects the data it needs from the response text
    • Modifies the DOM to reflect any changes

An Example: Login

  • User clicks the 'Login' button
  • In the Login button's onclick handler:
    • Collect the username and password values
    • Create an XMLHttpRequest object
    • Set URL to handler page, add username/password parameters, add callback
    • Submit the request
  • In the server-side page (e.g. Node.js)
    • Username and password are extracted from the request
    • The username and password are compared to the database data
    • Response is the user's UUID/name, empty otherwise
  • In callback function:
    • If the response was empty: show login page again
    • Otherwise: store UUID/name, update the user interface

Architecture

A diagram showing the various components involved with AJAX

Response Formats

  • Safe response formats:
    • Comma-separated values (CSV)
    • JSON
    • XML
    • Plaintext
  • Unsafe response formats:
    • HTML
    • JavaScript

Same Origin Policy

  • Some browsers may restrict AJAX requests to the same:
    • Protocol
    • Host
    • Port number

AJAX Example

  • Load a page that returns a plain text response:

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
    if ((xmlHttpRequest.readyState === 4) && 
        (xmlHttpRequest.status === 200)) {
        if (xmlHttpRequest.responseText === 'true') {
            // launch!
        }
    }
};
xmlHttpRequest.open('GET','timeToLaunch.php',true);
xmlHttpRequest.send();
                        

AJAX Example

  • Load a page that returns a CSV text response:

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
    if ((xmlHttpRequest.readyState === 4) && 
        (xmlHttpRequest.status === 200)) {
        var data = xmlHttpRequest.responseText.split(",");
        // do something with data[0], data[1], etc.
    }
};
xmlHttpRequest.open('GET','getSensorReadings.do',true);
xmlHttpRequest.send();
                        

Response - readyState

  • 0 - uninitialized
  • 1 - loading
  • 2 - loaded
  • 3 - interactive
  • 4 - complete

Response - status (HTTP status codes)

  • 200 - successful GET/POST
  • 302 - redirect
  • 401 - unauthorized (must login)
  • 403 - forbidden (invalid permissions)
  • 404 - file not found
  • 500 - server-side error

Response - responseText and responseXML

  • responseText
    • Plaintext
    • CSV/TSV
    • JSON
  • responseXML
    • XML
      • This is a DOM object of already parsed XML

jQuery AJAX Example

  • Load a page that returns a plain text response:

$.ajax("timeToLaunch.php")
    .done(function(response) {
        if (response === 'true') {
            // launch!
        }
    })
    .fail(function() {
        console.log("error loading launch polling page");
    })
    .always(function() {
        console.log("ajax complete");
    });
                        

AJAX, JSON, and XML

JSON

JavaScript Object Notation (JSON)

  • Originally, dictionaries in JavaScript were called objects
    • The notation used was called 'object notation'
  • The hierarchical data format JSON was created based on its syntax
    • Stores exactly one JavaScript-syntax 'object'
    • Objects are typically dictionaries, but could also be an array
    • Names and values must always be quoted (traditionally, double quoted)

JSON Example

  • This JSON is a dictionary, which contains an array

{"courseCode": "CSCI3230u",
 "courseName": "Web Application Development",
 "classList": [
    {"sid": "100000001", "fName": "Phillip", "lName": "Fry"},
    {"sid": "100000001", "fName": "Turanga", "lName": "Leela"},
    {"sid": "100000001", "fName": "Hubert",  "lName": "Farnsworth"},
    {"sid": "100000001", "fName": "Amy",     "lName": "Wong"},
    {"sid": "100000001", "fName": "Bender",  "lName": "Rodriguez"},
    {"sid": "100000001", "fName": "Hermes",  "lName": "Conrad"}
 ]
}
                        

JSON Example

  • Converting from JSON to JavaScript objects:
    
    var json = '{"firstName":"Robert","lastName":"Smith","age":"29","birthPlace":"Prince George"}';
    var obj = JSON.parse(json);
                                    
  • Converting from JavaScript objects to JSON:
    
    var customer = { firstName: 'Robert',
                      lastName: 'Smith',
                           age: 29,
                    birthPlace: 'Prince George'};
    var customerJSON = JSON.stringify(customer);
                                    

JSON Example

  • There are many tutorials showing code like this:
    
    var json = '...';
    var obj = eval(json);
                                    
  • This is potentially a big security risk

JavaScript JSON AJAX Example

  • Load JSON data from JavaScript:

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
    if ((xmlHttpRequest.readyState === 4) && 
        (xmlHttpRequest.status === 200)) {
        var data = JSON.parse(xmlHttpRequest.responseText);
        console.log("maxTemperature: " + data['maxTemp']);
    }
};
xmlHttpRequest.open('GET','getStats.py',true);
xmlHttpRequest.send();
                        

jQuery JSON AJAX Example

  • Load JSON data from jQuery:

$.getJSON('getStats.py', function(data) {
    $.each(data, function(key, value) {
        if (key === 'maxTemp') {
            console.log("maxTemperature: " + value);
        }
    });
});
                        

AJAX, JSON, and XML

XML

XML

  • XML has a bit of a split personality
    • XML standards and de facto standards
    • Create your own XML format

Standards and de Facto Standards

  • News feeds (e.g. RSS, Atom)
  • Computer communication languages (e.g. SOAP)
  • Human communication languages (e.g. XMPP)
  • Document formats (e.g. HTML, ODT)
  • Configuration languages (e.g. Ant, Android, iOS)

Create Your Own XML Format

  • Anyone can make their own XML format:

<?xml version="1.0" ?>
<bobs-pc-shack-inventory>
   <computers>
      <laptop price="399.99" cpu="i5-3570" />
      <desktop price="799.99" cpu="i7-2600" />
   </computers>
   <parts>
      <video-card price="149.99" chipset="GTX 670" />
      <video-card price="549.99" chipset="Titan" />
   </parts>
</bobs-pc-shack-inventory>
                        

XML Structure

  • XML can be made up from:
    • Elements
    • Attributes
    • Attribute values
    • Text

<price value="199.99" />
<price>199.99</price>
<computer><price value="199.99" /></computer>
                        

XML Structure

The DOM of the XML document

Parsing XML

  • Parsing XML in JavaScript:

var rawXML = '\
<inventory>\
   <computers>\
      <laptop price="499.99" cpu="i5-3570" />\
      <laptop price="549.99" cpu="i5-3570" />\
      <laptop price="999.99" cpu="i7-2600" />\
   </computers>\
</inventory>';
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(rawXML,"text/xml");
                        

Parsing XML

  • jQuery has a convenience function for parsing XML:

var rawXML = '\
<inventory>\
   <computers>\
      <laptop price="499.99" cpu="i5-3570" />\
      <laptop price="549.99" cpu="i5-3570" />\
      <laptop price="999.99" cpu="i7-2600" />\
   </computers>\
</inventory>';
var xmlDoc = $.parseXML(rawXML);
                        

JavaScript XML AJAX Example

  • Load XML data from JavaScript

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
    if ((xmlHttpRequest.readyState == 4) && 
        (xmlHttpRequest.status == 200)) {
        var xmlData = xmlHttpRequest.responseXML;
        var person = xmlData.getElementsByTagName('person')[0];
        var firstNameVal = person.getAttribute('firstName');
        console.log("first name: " + firstNameVal);
    }
};

var id = 17;
xmlHttpRequest.open('GET', 'getPrices.aspx?index=' + id, true);
xmlHttpRequest.send();
                        

jQuery XML AJAX Example

  • Load XML data from jQuery

$.get('inventory.xml', function(xmlDoc) {
     var result = '<ul>';
     $(xmlDoc).find('laptop').each(function() {
        result += '<li>' + $(this).attr('cpu') + '</li>';
     });
     result += '</ul>';
     $('#output').html(result);
});
                        

AJAX, JSON, and XML

Open Data

YouTube API

  • Keyword search:
    • http://gdata.youtube.com/feeds/api/videos?vq=...
  • Most popular videos:
    • http://gdata.youtube.com/feeds/api/standardfeeds/most_popular
  • Videos in channel:
    • http://gdata.youtube.com/feeds/api/users/.../uploads

YouTube API - Relevant fields

  • URL to video:
    • item.link[0].href;
  • Video title:
    • item.title.$t;
  • Author name:
    • item.author[0].name.$t;
  • Date published:
    • item.published.$t;
  • Video ID:
    • item.id.$t;

Other APIs

  • Exchange rates (JSON, paid):
    • openexchangerates.org
  • Weather (RSS/XML):
    • http://weather.yahooapis.com/forecastrss?w=24405663&u=c
  • Government of Canada Open Data (CSS, XML, JSON):
    • http://open.canada.ca/data/en/dataset
  • Government of Ontario Open Data (mostly CSS, XLSX):
    • https://www.ontario.ca/open-data
  • City of Toronto Open Data (CSS, XML, JSON):
    • http://www1.toronto.ca/wps/portal/contentonly?vgnextoid=1a66e03bb8d1e310VgnVCM10000071d60f89RCRD

Wrap-Up

  • In this section, we learned about:
    • AJAX
      • JavaScript
      • jQuery
    • JSON
    • XML
    • Open Data