QuickCheck
Review promises: Handling uncertainty
Review AJAX: Why is it useful? How do we use it?
Practice AJAX with text response
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:
const URL_BASE = "";
// Step 1. Write a function to "fetch" data from a URL
function callAjax() {
let url = URL_BASE + "?query0=value0"; // some requests require parameters
fetch(url)
.then(checkStatus)
//.then(resp => resp.text()) // include if your data comes in text
//.then(resp => resp.json()) // include if your data comes in JSON
.then(processData)
.catch(console.log);
}
// Step 2: Implement a function to process the respsonse data. You may want to break this apart
// into multiple functions.
function processData(responseData) {
// Do something with your responseData! (build DOM, display messages, etc.)
}
// Step 3. Include the checkStatus function
function checkStatus(response) {
if (!response.ok) { // response.status >= 200 && response.status < 300
throw Error("Error in request: " + response.statusText);
}
return response;
}
JS
We initiate a fetch
of a URL
fetch
call returns a Promise
object.then
method on a Promise
object returns a Promise
object.then(checkStatus)
checks the status of the response to makes sure the server responded with an OK. The
result of that first .then
is another Promise
object with
the response as the value of the Promise.
.then(resp => resp.json())
which also returns
a Promise
object with a JSON object as the value
.then(processData)
which will do something with the response
from the server.
.catch
method on the Promise
chain
Chaining of Promises gives us a nice data flow, like down a pipe!
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 last problem - 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. Here is a starter JS file.
Solution (JavaScript)
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"
...
Template Plain Text Response
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)