Recap: Ajax

Ajax

Ajax

ajax diagram

Promises

promise
A JS object that executes some code that has an uncertain outcome

Promises have three states:

Example: “I promise to post homework 4”
Pending: Not yet posted
Fulfilled: Homework 4 posted
Rejected: Wrong homework posted, or not posted in time

Promises example: defining a promise:

Note, for this class, you do not need to know how to define a promise. This slide is just here to help explain how to define them, as our Ajax Promise code uses them.


        var promise = new Promise( function( resolve, reject ) {
            // do something uncertain (like make an ajax call)

            if ( /* success */ ) {
                resolve();
            } else {
                reject();
            }
        });
    

JavaScript

Promises example: using a promise

var promise = new Promise( ... promise definition ... );
promise
    .then( function( params... ) {
        /* Promise resolved -- handle success case */
    })
    .catch( function( params... ) {
        /* Promise rejected -- handle failure case */
    });
    

JavaScript

Promises example: using our Ajax Promise

var url = "my/url/some/file.txt";
var promise = new AjaxGetPromise( url );
promise
    .then(handleResponse)
    .catch(handleError);
...
...
function handleResponse(responseText) {
    /* handle successful ajax request */
}
function handleError(errorMsg, statusCode) {
    /* handle error case */
}
    

JavaScript

What's good about Promises:

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

var 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

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

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:

What is JSON used for?

JSON data comes from many sources on the web:

JSON is the de facto universal format for exchange of data

JSON Rules!

JSON has a few rules that differ from regular JS:

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:

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

var data = JSON.parse(json);
var title = data.window.title;
var coord = data.image.coords[2];
var len = data.messages.length;
var y = data.messages[len - 1].offset[1];