CSE 154

Week 4 Section: AJAX with JavaScript

Section Agenda

QuickCheck: Timers Practice

Review AJAX: Why is it useful? How do we use it?

Practice AJAX with different response formats

AJAX

Why is it useful?

  • The web is full of data - often, websites "ask" for data from servers which hold different types of data (txt, json, images, databases, etc.)
  • What we know about JS so far does not give us any way to process data outside of our JS program. That's where AJAX comes in!

How do we use it?

  • fetch! (a built-in JavaScript function)
  • A touch of Promises to elegantly control success (200) vs. error (non-200) responses from a server

Ajax fetch template

When we make a call to fetch data (whether it's HTML, txt, JSON, etc) we use a function in JavaScript called fetch, which takes a URL path to fetch data from.

Here's the general template you will use for most AJAX code:

// inside module pattern
... // Step 1. Write a function to "fetch" data from a URL
function callAjax(){
  let url = URLBASE + "?query0=value0"; // some requests require parameters
  fetch(url, {mode: "cors"}) // mode cors for talking with our web services
    .then(checkStatus)
    // .then(JSON.parse) /* uncomment if your data comes in JSON instead of text)
    .then(successFunction)
    .catch(console.log);
}

// Step 2. Write a function to do something with the response text (a string if
// you don't have .then(JSON.parse) in the fetch call chain, otherwise a JSON object)
function successFunction(responseData){
  // do something with the responseData, like adding to the DOM
}

// Step 3. Copy/paste the checkStatus function which uses Promises to control
// success vs. errors in request
function checkStatus(fetchResponse) {  // boiler plate code given out
  if (response.status >= 200 && response.status < 300 || response.status == 0) {
    return response.text(); // return string text of response if server marked it as successful
  } else {                  // otherwise, return error response object
    return Promise.reject(new Error(response.status + ": " + response.statusText));
  }
}

JS (full template)

Alright, let's play fetch with pets!

Exercise 1: Ajax Pets

Given this ajaxpets-starter.zip (HTML, CSS, and JS template), create an AJAX-powered gallery of pet images that allows you to switch between kitty and puppy images without reloading the page. You can view the finished product here.

super special ajax pets pet

Exercise 1: Ajax Pets API URL

Service URL: https://courses.cs.washington.edu/courses/cse154/webservices/pets/ajaxpets.php

Query Parameters (required):
?animal=value

Details: animal is the name of the query parameter you need to assign a value to. This API recognizes either a value of puppy or kitty.

Example Request (with puppy as the value):
https://courses.cs.washington.edu/courses/cse154/webservices/pets/ajaxpets.php?animal=puppy

Exercise 1: Ajax Pets API Response Format

Response Format: Plain Text


"https://path/to/pet/img0.jpg"
"https://path/to/pet/img1.jpg"
"https://path/to/pet/img2.jpg"
"https://path/to/pet/img3.jpg"
...
            

Template Plain Text Response

Exercise 1: Ajax Pets Implementation

The provided starter code includes a module-pattern template we've been using to get you started, named ajaxpets.js. You will need to implement the JavaScript to incorporate AJAX and make a request with the Ajax Pets API URL with the parameter animal of value kitty or puppy, depending on which radio button is selected.

When a request returns a response successfully with the plain text response of image paths, write JS to add img tags as children to the #pictures div for each image path returned on a new line.

Exercise 1: Solution

Solution (JavaScript)

Exercise 2: Recipes

Given this recipe-starter.zip (HTML, CSS, and JS module template), add ajax to the recipe.js that fetches and displays recipe information on the page whenever a different recipe radio button is selected.

expected output for recipes exercise

Exercise 2: Recipes API URL

Service URL: https://courses.cs.washington.edu/courses/cse154/webservices/recipe/recipe.php

Query Parameters (Required):
?recipe=value

Details: recipe is the name of the query parameter you need to assign a value to. This API recognizes any of the radio button values on the provided recipe.html page.

Example Request (with peas as the value):
https://courses.cs.washington.edu/courses/cse154/webservices/recipe/recipe.php?recipe=peas

Exercise 2: Recipes API Response Format

Response Format: JSON

{ "recipe": {
    "information": {
      "name": ...,
      "image": ...
    },
    "ingredients": {
      "item": [{
          "amount": ...,
          "text": ...
        }, ... {
          "amount": ...,
          "prep": ...,
          "text": ...
        }
      ]
    },
    "directions": {
      "step": [
        ..., ...
      ]
    }
  }
}

Template JSON response (shortened)

Exercise 2: Recipes Implementation

When a radio button is clicked make a fetch to the recipes URL with the recipe query parameter assigned value of the selected radio button.

For example, the radio button for "peas" has a value of "peas". To get the JSON specific to the peas recipe you'll need to add a query/value pair of recipe=peas to the request URL. Try it!

You must parse the results and fill the #recipes-area section with:

  1. An img tag with the recipe's image
  2. A h1 containing the title
  3. A p containing the recipe's description text
  4. A h2 with the text "Ingredients:"
  5. A ul filled with a list of the recipe's ingredients.

Check out a complete running version here.

Exercise 2: Solution

Solution (JavaScript)

Exercise 3: Number Trivia! (a public API example)

Numbers API screenshot

This is a short exercise, but shows how to use one of thousands of API's available publically on the web. Some are more complicated than others (this is a great example of the importance of clear documentation!) and some require tokens or keys (which is good for security reasons, but takes an extra step).

The Numbers API is one of the simplest APIs available to get started with fetching data from the web without needing a token.

Numbers API Details

Service URL: http://numbersapi.com/

Query Parameters (Required): number

Note: this API doesn't have the "query=value" format we saw in the other two web services - some APIs have a bit of a different format which you can find in the documentation.

Details: Replace number with any integer number (e.g. 154), or random to get trivia about a number. Response is returned as a single plain text string.

Example Requests

Using the Numbers API: A Simple Example

example output of number-trivia
          exercise

Given this starter numbers.html, write a JavaScript program numbers.js to take an integer value from a number text box and fetch a trivia fact about that number when the "Fetch Number Fact!" button is clicked, displaying the result text in the #output paragraph.

If the button is clicked but the text input is empty, or the "Fetch Random Number Fact!" button is clicked, a random number trivia fact should be fetched and displayed.

Running Demo

Exercise 3: Solution

Solution (JavaScript)