QuickCheck: Timers Practice
Review AJAX: Why is it useful? How do we use it?
Practice AJAX with different response formats
Why is it useful?
How do we use it?
fetch
! (a built-in JavaScript function)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));
}
}
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.
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
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"
...
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.
Solution (JavaScript)
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.
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
Response Format: JSON
{ "recipe": {
"information": {
"name": ...,
"image": ...
},
"ingredients": {
"item": [{
"amount": ...,
"text": ...
}, ... {
"amount": ...,
"prep": ...,
"text": ...
}
]
},
"directions": {
"step": [
..., ...
]
}
}
}
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:
Check out a complete running version here.
Solution (JavaScript)
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.
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
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.
Solution (JavaScript)