JSON and Promises
In this lab, you will use fetch
and Promises to retrieve a
web-based data set that is processed asynchronously.
You will need to consult the Bootstrap and JavaScript documentation throughout this lab.
Starting Code
Download the following files to get started:
index.html
- A starter Bootstrap HTML page.countries.json
- A JSON file containing a list of valid countriesdata.js
- A started JavaScript file
You will only modify and submit the data.js
file. You are encouraged
to examine the countries.json
file to develop an understanding of the
structure of the data.
This lab is using JSON data provided by The World Bank. You do not need to study this API, but it is provided here as reference.
Step 1: Asynchronous function calls
Your first step is to complete the self-executing initialization
function issue a query to the World Bank API using fetch()
,
then processing the JSON data retrieved. Implement the
processJSON()
function based on the embedded comment to
create an object to return. Loop through the data to add each entry
to the returned object accordingly. In the fetch()
handling,
the returned object should be passed directly to redraw()
.
Step 2: Processing form requests
Your next step is to modify the initialization routine to add an
event listener for the form. In the event listener, you need to prevent
the page from reloading (calling preventDefault()
on the
event) then passing form data to runQuery()
. The implementation
of runQuery()
should be similar to Step 1, but using the form
data to customize the query.
Step 3: Working with Promises
Your final step is to complete and use the validateForm()
function for asynchronous processing of the form data. You will need to
change the initialization routine so that the form's event listener
uses validateForm()
to get a Promise, passing the resolved
value to runQuery()
rather than getting the form data
directly. If the validation fails (the Promise is rejected), get the
error message and put it into the '#metadata'
element.
Swap that element's classes to use the .text-danger
class
instead of .text-muted
to make the text red.
In validateForm()
, you will need to check three things:
the country is among a small number of allowed countries, the dates
are years between 1960 and 2023, and the start date comes before the
end date. To check if the country is allowed, use fetch()
to retrieve the countries.json
file. (You can hard-code
https://w3.cs.jmu.edu/kirkpams/343/labs/lab8/countries.json
as the URL.) Find the country among that list, using a case-insensitive
comparison (e.g., "france"
should match "France"
),
then get the associated ID field. For checking the dates, you should
use parseInt()
on the date values to ensure they are valid
integers first. If everything is fine, use resolve()
to return
the code ID and the date search string; otherwise, use reject()
with a reasonable error message.
Submission
When you are finished, upload just your data.js file to Canvas.