Welcome!
Everything is fine.

Ajax and LocalStorage

Ajax is not lengthy, but it is odd and surprising.

LocalStorage is useful and much easier than Ajax. We'll use it in our final project.

Plan

  1. Announcements
  2. Recap Ajax and LocalStorage
  3. Answer your Ajax questions
  4. Breakout

Announcements

  1. Grading Status
  2. Quizzes Hints (also in the assignment)
    • Use the class syntax from our discussion of OOP (bank accounts and such)
    • Do not reference the questions array from your class. The constructor and the addToDOM methods only use their arguments. They use no global variables.
    • Maybe define a helper function for the constructor
    • Remember how to add things to the document.
    • Write out the HTML first. Only then start writing JS that writes the HTML.
    • How to grab a random button and test your grading code
    • Avoid ID for dynamic elements.

Breakout Session

BO

Start breakout session

Recap Ajax

Ajax makes a "side" request to the server and sets up a "catcher" to catch and deal with the response.

slideshow

Collatz Example

Timing

Which message is printed first?

$.get('characters.json',function (data) {
    console.log('Done. Got '+data);
});
console.log('Finally done.');

Demo

get random HP character

Answer the following questions:

  1. How long does it take for the data to arrive?
  2. Does it take the same amount of time every time?
  3. What URL is the data gotten from?
  4. If you visit that URL (just copy/paste it into your browser location bar), you can see the actual data that is sent. Or look at the serverData global variable.

Coffeerun Examples

Let's look at some examples:

coffeerun ajax demo subset is a subset of the coffeerun code that allows us to play with the Heroku Cloud database. It's not integrated with the rest of coffeerun.

The demo:

  1. I'll open up two browsers onto the page linked above.
  2. You can also open up a browser to that page.
  3. I'll putOrder(order1)
  4. I'll getOrder(key1) in both browsers. You can, too.

That demonstrates that the data has left my browser and gone to a cloud-based database server where it's accessible to all of us. Very cool!

We are omitting:

  • authentication/authorization
  • limitations on duration and size and contents
  • other security issues

Still, this is very cool because:

  1. We can send JS data to a persistent data store outside our browser
  2. We can share that data with others

Imagine that the data is posts and likes, and pretty soon, we can build FaceBook.

Coffeerun Remote Database API

The database API has to change because the methods like .get(id) and .getAll() can no longer return values, but instead have to be written to take a callback function. So,

not this:

    var customerIdArray = Object.keys(this.db.getAll());
    // code using customerIdArray ...

but this:

    this.db.getAll(function (obj) {
        var customerIdArray = Object.keys(obj);
        // code using customerIdArray ...
        });

That changes the code in the truck module. We won't go into all those changes, but you can explore if you want.

Here's the demo. It starts with a popup asking whether to use the cloud-based database; click "confirm" for "yes".

coffeerun with Ajax in ES6

Coffeerun Code

/* Rewritten by Scott, Summer 2020. This defines a class
 RemoteDataStore that implements the same API as the DataStore class,
 although the constructor has a different signature (adding the url).

 The methods get() and getAll() differ in having requiring a callback function
 but in Chapter 14 they make that argument optional and return a promise instead, but
 we won't get into promises. */

class RemoteDataStore {
    // instance variables
    serverUrl = null;

    constructor (url) {
        if (!url) {
            throw new Error('No remote URL supplied');
        }

        this.serverUrl = url;
    }

    add (key, val) {
        $.post(this.serverUrl, val, function (serverResponse) {
            console.log(serverResponse);
        });
    }

    getAll (callback) {
        $.get(this.serverUrl, function (serverResponse) {
            console.log('getAll serverResponse: ',serverResponse);
            callback(serverResponse);
        });
    }

    get (key, callback) {
        $.get(this.serverUrl + '/' + key, function (serverResponse) {
            console.log('get '+key+' serverResponse: ',serverResponse);
            callback(serverResponse);
        });
    }

    remove (key) {
        $.ajax(this.serverUrl + '/' + key, {
            type: 'DELETE'
        });
    }
}

export { RemoteDataStore };

Here's the working coffeerun with Ajax

Here's the old coffeerun without Ajax

REST API

There was some mysterious stuff in the reading about REST APIs and these HTTP "verbs" like "get", "post", "put" and "delete". We won't dig to far into this, but here's the basic idea:

  • the server hosts a database
  • the interaction with the database is by basic HTTP
  • the database is made of records that have some kind of key (so, key/value pairs comes up again)
  • the database is found by some kind URL like coffeeorders

So, we have stuff like

  • GET /coffeeorders/ lists (returns) all the records
  • POST /coffeeorders/ along with a record adds that record to the database
  • DELETE /coffeeorders/ deletes all records

With with a key at the end of the URL:

  • GET /coffeeorders/scott@wellesley.edu lists (returns) that one record (my order)
  • PUT /coffeeorders/scott@wellesley.edu along with a record replaces that one record (my order)
  • DELETE /coffeeorders/scott@wellesley.edu deletes that one record

Notice that certain combinations aren't allowed. PUT requires a key, and POST requires the record to be brand new. If you want more, see REST PUT vs POST

REST APIs have become a very popular web API.

Oddly, the verbs like PUT and DELETE are not part of HTML, so you can't use an ordinary form, you must use Ajax in order to use a REST API. That still bothers me....

LocalStorage

I'll demo the LocalStorage persistent grocery example from the reading. Hopefully you did so, but I'll re-do it so you can ask questions.

Dev Tools in Firefox:

  1. open the developer tools,
  2. switch to the "Storage" tab (highlighted in blue in the screenshot below)
  3. toggle open the "LocalStorage" part of the page
  4. click on the origin for the page you're on or interested in (highlighted in blue)
  5. See the key/value pairs, as shown:

Similar in Chrome, though not identical.

Demo:

  1. add a few items to the list
  2. delete a few items from the list
  3. save the list
  4. reload the page, and see that your changes were saved!

Your Questions

I'll answer your questions

Summary

Ajax

  • Ajax allows us to send (POST) and receive (GET) data from a server without having to leave our current page.
  • We can also use the .ajax jQuery method if we want to use other verbs like PUT or DELETE.
  • Ajax requests are asynchronous, so we must supply a callback function if we care about the response from the server (usually we will, but sometimes we might not).

LocalStorage

  • We can save data to the browser using a generic key/value store
  • localStorage.key = value