Lecture 12

Introduction to JSON and AJAX

I'm working on a creative project for another class right now and its nowhere near as cool as our students'...

Conner

Agenda for today's Alphabet Soup

  • Notes:
    • Seating chart for the midterm in GUG 220 is posted
    • Melissa will have 1 on-line OH to go over APIs and Fetch or other non-homework course material tomorrow. Look on Piazza for information.
  • Finishing up on DOM Tree traversal
  • JSON
  • AJAX
  • CP3

CSE 154 Modules

  1. Webpage structure and appearance with HTML5 and CSS.
  2. Client-side interactivity with JS DOM and events.
  3. Using web services (API's) as a client with JS.
  4. Writing JSON-based web services with PHP.
  5. Storing and retreiving information in a database with MySQL and server-side programs.

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)

But first... JavaScript objects

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

JS (example)

In JavaScript, you can create a new object without creating a "class" like you do in Java

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

myobj.field87 = "wubba wubba wubba";

JS (example)

Example

let fidgetSpinner = {
  owner: "Nate Spencer",                           // string
  grade: "Junior",                                 // string
  "zip-code": 90210,                               // number
  price: 3.95,                                     // number
  colors: ["red", "green", "purple"],              // array
  getChoice: function() { return this.owner + " bought " + this.colors[1]; }
};
console.log(fidgetSpinner.price);         // 3.95
console.log(fidgetSpinner.colors[2]));    // purple
console.log(fidgetSpinner.getChoice());   // Nate Spencer bought green
console.log(fidgetSpinner["zip-code"]);   // 90210
console.log(fidgetSpinner.zip-code]);     // error

JS (example)

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 put in quotes - optional unless there is a space or dash (e.g. "zip-code" above which must be accessed using [] notation)

JSON Practice: here, here, and here.

Examples of JS objects we've seen so far

  • DOM elements
  • document, window

Groupizer/Randomizer

What do you think the JSON should look like for storing the group and member names for the Groupizer/Randomizer?

Groupizer user interface Randomizer user interface

Randomizer and actual JSON file

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 stringify/parse example

> let point = {x: 1, y: 2, z: 3}
> point
> {x: 1, y: 2, z: 3}
> let s = JSON.stringify(point);
> s
> "{"x":1,"y":2,"z":3}"
> s = s.replace("1", "4");
> "{"x":4,"y":2,"z":3}"
> let point2 = JSON.parse(s);
> point2
> {x: 4, y: 2, z: 3} 

JS (console)

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 quoted
  • All property/field names must be quoted
  • Values can be:
    • Number (23)
    • String ("string has to be quoted, 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",  // with double quotes
  "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 called data.

for instance, the window's title is data.window.title

  • What the debug flag is set to?
  • 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 title = data.window.title;             // title === "Sample Widget"
let debug = data.debug;                    // debug === "true"
let coord = data.image.coords[2];          // coord === 350
let len = data.messages.length;            // len === 3
let y = data.messages[len - 1].offset[1];  // y === 15

JS

AJAX

web application:
a dynamic web site that feels like a desktop application
AJAX:
a specific style of using JS to call out to the server for more information
AJAX with the Fetch API:
A newer, easier way to accomplish AJAX calls
Promise:
a JS object that is useful for dealing with uncertainty in your program

Web Applications

All of the pages that we've made up until now have content, style, and behavior.

Web applications are webpages that pull in additional data and information as the user progresses through them, making it feel similar to a desktop application.

Some motivations for making web pages into web applications:

  • Better user experience
  • Less data sent across the wire
  • Leads to good software architecture:
    • Client handles display, server serves up data

Synchronous requests

synchronous request diagram

Why are synchronized requests are problematic?

Your code waits for the request to completely finish before proceeding.

It is easier to program for synchronous behavior, but the user's entire browser LOCKS UP until the download is completed, which is a terrible user experience (especially if the page is very large or slow to transfer)

Asynchronous requests

asynchronous request diagram

Watching requests

Use the inspector, watch the network tab to see the requests that go out.

Watching network requests

Example from Randomizer

APIs

Application Program Interfaces (APIs)

An application programming interface (API) is a communication protocols that allows two pieces of software to communicate.

A Web API is a set of pre-defined URLs with parameters that allow a user to get information from a web server.

API examples we'll be demonstrating in class

AJAX Demo

On Monday we will be talking about "how" to actually get data from the API.

But the first thing you need to do to use an API is Read the documentation

  • Do you need a key to use the API?
  • What are the different types of responses (txt, JSON, HTML, etc.)?
  • What is a use case or a question you could ask with the data available? How could you use this data on your page?

Let's look at NASA API

Result: Astronomy Picture of the Day

Running through MAMP

In preparation for working with our server side code we installed and and configured a server on our machine called MAMP (Mac Apache MySQL PHP)

Now instead of your urls being file:///Users/lauren/Desktop/cse154/hw2-set-bricker/set.html

We will run them through locahost, e.g.

  • Mac:
    localhost:8888/154-19sp/hw2-set-bricker/set.html
  • Windows:
    localhost/154-19sp/hw2-set-bricker/set.html

CORS error

The fetch interaction will not work between some clients and servers due to configurations on the server (whether the server allows "Cross Origin Requests")

example of the cors problem

Demo:

  • APOD running as a file:/// vs localhost/ or localhost:8888/
  • Randomizer running as a file:/// (error) vs localhost/ or localhost:8888/
CP3 and Weekend Homework

CP3 is out - you will be dynamically adding data from an API to your webpage in response to an event.

In order to effectively do this, you must first figure out what API you want to use and how you want to use

Fill in this form by Monday classtime.