Recap: Ajax

Ajax

  • using JS to download data (or other stuff) from the server in the background
  • allows dynamically updating a page without making the user wait
  • JSON is now more common than XML, but they are both just ways to store data
  • not a programming language; a particular way of using JavaScript
  • avoids the "click-wait-refresh" pattern
  • examples: UW's CSE 14x Diff Tool, Practice-It; Amazon product pages, most auto-complete search features

Ajax Code Skeleton

//include this code, based on: https://developers.google.com/web/updates/2015/03/introduction-to-fetch
function checkStatus(response) {  
    if (response.status >= 200 && response.status < 300) {  
        return response.text();
    } else {  
        return Promise.reject(new Error(response.status+": "+response.statusText)); 
    } 
}
    
function callAjax(){
    let url = ..... // put url string here
    fetch(url, {credentials: 'include'}) // include credentials for cloud9
       .then(checkStatus)
       .then(function(responseText) {
            //success: do something with the responseText
        })
       .catch(function(error) {
           //error: do something with error
       });
}

Ajax Code Skeleton (slight variation)

function checkStatus(response) {   
   ...
}
    
function callAjax(){
    let url = ..... // put url string here
    fetch(url, {credentials: 'include'}) // include credentials for cloud9
       .then(checkStatus)
       .then(handleResponse)
       .catch(handleError);
}

function handleResponse(responseText){
    //success: do something with the responseText
}

function handleError(error){
    //error: do something with error
}

JSON

JSON
JavaScript Object Notation

A data format that represents data as a set of JavaScript objects invented by JS guru Douglas Crockford of Yahoo! natively supported by all modern browsers (and libraries to support it in old ones)

JavaScript objects

let myobj = {
  fieldName1: value1,
  ...
  fieldName: value
};

JavaScript

In JavaScript, you can create a new object without creating a "class"

You can add properties to any object even after it is created:

myobj.field87 = "wubba lubba";

JavaScript

let person = {
    name: "Philip J. Fry",                           // string
    age: 23,                                         // number
    "weight": 172.5,                                 // number
    friends: ["Farnsworth", "Hermes", "Zoidberg"],   // array
    getBeloved: function() { return this.name + " loves Leela"; }
};
alert(person["age"]);                  // 23
alert(person.weight);                  // 172.5
alert(person.friends[2]));             // Zoidberg
alert(person.getBeloved());            // Philip J. Fry loves Leela

an object can have methods (function properties) that refer to itself as this
can refer to the fields with .fieldName or ["fieldName"] syntax
field names can optionally be put in quotes (e.g. weight above)

Examples of JS objects:

  • DOM elements
  • document, window
  • XMLHttpRequest
  • Promise

JavaScript Objects and JSON

JSON is a way of saving or storing javascript objects. (The technical term is "serializing" which is just a fancy word for turning an object into a savable string of characters)

Browser JSON methods:

  • JSON.parse( /* JSON string */ ) -- converts JSON string into Javascript object
  • JSON.stringify( /* Javascript Object */ ) -- converts a Javascript object into JSON text

What is JSON used for?

JSON data comes from many sources on the web:

  • web services use JSON to communicate
  • web servers store data as JSON files
  • databases sometimes use JSON to store, query, and return data

JSON is the de facto universal format for exchange of data

JSON Rules!

JSON has a few rules that differ from regular JS:

  • Strings must be double-quoted
  • All property/field names must be quoted
  • Values can be:
    • Number (23)
    • String ("string has to be quoted, like this" , 'or like this')
    • Boolean (true, false)
    • Array ( [ "value1", 24, true, 'hallo' ] )
    • Object ( { "nested" : "object", "which" : { "can" : "have more nested objects" } } )
    • null

Numerous validators/formatters available, eg JSONLint

JSON limitations

JSON can't handle certain data types, so these things just fall out of the object if you try to make JSON strings out of them:

  • Function
  • Date
  • RegExp
  • Error

To get Date objects or RegExp objects into your JSON, you could extract them as strings, and then rebuild them from strings.

However, since JSON is ideal for communicating across different types of systems, you can't put Javascript functions in JSON. Other languages wouldn't be able to read JSON effectively if it had Javascript code in it.

(This is also why Dates and RegExps can't go into the JSON object -- other languages wouldn't know how to interpret them for what they are.)

Valid JSON

{                          // no variable assignment
  "first_name": 'Bart',    // strings and properties must be quoted
  'last_name': "Simpson",  // single or double quotes both work
  "age" : 13,              // numbers can be here without quotes
  "cowabunga": true        // booleans can be here without quotes
}                          // no semicolon at the end

JSON

JSON exercise:

Given the JSON data at right, what expressions would produce. Assume the JSON data is stored in a string variable called json.

  • The window's title?
  • The image's third coordinate?
  • The number of messages?
  • The y-offset of the last message?
{
    "window": {
        "title": "Sample Widget",
        "width": 500,
        "height": 500
    },
    "image": {
        "src": "images/logo.png",
        "coords": [250, 150, 350, 400],
        "alignment": "center"
    },
    "messages": [
        {"text": "Save", "offset": [10, 20]},
        {"text": "Help", "offset": [ 0, 50]},
        {"text": "Quit", "offset": [30, 15]}
    ],
    "debug": "true"
}

Answers:

let data = JSON.parse(json);
let title = data.window.title;
let coord = data.image.coords[2];
let len = data.messages.length;
let y = data.messages[len - 1].offset[1];
{
    "window": {
        "title": "Sample Widget",
        "width": 500,
        "height": 500
    },
    "image": {
        "src": "images/logo.png",
        "coords": [250, 150, 350, 400],
        "alignment": "center"
    },
    "messages": [
        {"text": "Save", "offset": [10, 20]},
        {"text": "Help", "offset": [ 0, 50]},
        {"text": "Quit", "offset": [30, 15]}
    ],
    "debug": "true"
}

Ajax Code Skeleton for JSON

//include this code, based on: https://developers.google.com/web/updates/2015/03/introduction-to-fetch
function checkStatus(response) {  
    if (response.status >= 200 && response.status < 300) {  
        return response.text();
    } else {  
        return Promise.reject(new Error(response.status+": "+response.statusText)); 
    } 
}
    
function callAjax(){
    let url = ..... // put url string here
    fetch(url, {credentials: 'include'}) // include credentials for cloud9
       .then(checkStatus)
       .then(function(responseJSON) {
            //success: do something with the responseJSON
        })
       .catch(function(error) {
           //error: do something with error
       });
}