Fetch

We can use the fetch() method to asynchronously (in the background) read data from a data source - such as a JSON file or a database. Reading data asynchronously means that the user is not blocked from doing other interactions with the current webpage while the data is being read from the data source.

Using fetch() to dynamically load a webpage's data and document.getElementById().innerHTML to dynamically output the data onto the screen allows a webpage to change its content in real-time. By using fetch(), we do not have to load a new webpage. Instead, we can update the current webpage based on new data that we read from a data source.

Using fetch() and document.getElementById().innerHTML allows for webpages to provide a smoother visual appearance to users, as the webpage does not need to reload. Only those parts of the webpage that need to be updated are changed. The rest of the webpage remains unchanged.

We use JSON to structure the data that is being read using fetch().

IMPORTANT: If we store a JSON object in an external file, then we need to put " quotes around the property keys, as shown below:

car_details.json

[
    {
        "model":"avensis",
        "colour":"red",
        "year":2017,
        "price":35000
    },
    {
        "model":"yaris",
        "colour":"white",
        "year":2015,
        "price":1000
    },
    {
        "model":"corolla",
        "colour":"white",
        "year":2017,
        "price":20000
    },
    {
        "model":"avensis",
        "colour":"red",
        "year":2015,
        "price":15000
    },
    {
        "model":"corolla",
        "colour":"black",
        "year":2010,
        "price":4000
    }
]

Example of reading data from a JSON file (Run Example)

<!DOCTYPE html>
<html>
<head>
<title>AJAX read JSON file example</title>
<script>
window.onload = () =>
{
    let url = `car_details.json`      /* name of the JSON file */

    fetch(url)
.then(response => response.json())
.then(jsonData => { let htmlString = `<table>` jsonData.forEach(car => { htmlString += `<tr> <td>${car.model}</td> <td>${car.colour}</td> <td>${car.year}</td> <td>${car.price}</td> </tr>` }) htmlString += `</table><br>${jsonData.length} records found.` document.getElementById('cars').innerHTML = htmlString }) } </script> </head> <body> <div id=cars>Car details will be listed here.</div> </body> </html>

In the above example, the fetch() method and related code is called when the webpage loads, as shown below:

window.onload = () =>

The JSON data will be read from the file called car_details.json

    let url = `car_details.json`      /* name of the JSON file */

Calls to the fetch() method are asynchronous. This means that the webpage does not wait for the fetch() method to return a value. Instead, the fetch() method is called in the background and the website continues to behave as it did before the fetch() method call was made. Once the fetch() method retrieves the JSON data, the .then() method takes the data that was read in from the file (i.e. response) and converts it into a JSON object. The second .then() method takes the JSON object that response was converted into (i.e. jsonData) to dynamically update the webpage (using document.getElementById('cars').innerHTML).

    fetch(url)
.then(response => response.json())
.then(jsonData => { let htmlString = `<table>` jsonData.forEach(car => { htmlString += `<tr> <td>${car.model}</td> <td>${car.colour}</td> <td>${car.year}</td> <td>${car.price}</td> </tr>` }) htmlString += `</table><br>${jsonData.length} records found.` document.getElementById('cars').innerHTML = htmlString })

Write code to improve the look-and-feel of the output from the above example, as shown here.

Coding your own fetch() methods

The code from the above example can be used as a template when you are coding your own fetch() methods. Only the code that is highlighted in red needs to change.

<!DOCTYPE html>
<html>
<head>
<title>AJAX read JSON file example</title>
<script>
window.onload = () =>
{
    let url = `car_details.json`      /* name of the JSON file */

    fetch(url)
.then(response => response.json())
.then(jsonData => { let htmlString = `<table>` jsonData.map(car => { htmlString += `<tr> <td>${car.model}</td> <td>${car.colour}</td> <td>${car.year}</td> <td>${car.price}</td> </tr>` }) htmlString += `</table><br>${jsonData.length} records found.` document.getElementById('cars').innerHTML = htmlString }) } </script> </head> <body> <div id=cars>Car details will be listed here.</div> </body> </html>

Adjust the code at this example so that the JSON data is held in a separate file, as shown here.

External JSON Files

There are many JSON datasets on the internet. We can use fetch() to access these datasets.

Write code to display a table of attractions to see in Dublin, as shown here. Use the dataset from this link, which is based on the dataset at (https://data.smartdublin.ie/dataset/b1a0ce0a-bfd4-4d0b-b787-69a519c61672/resource/b38c4d25-097b-4a8f-b9be-cf6ab5b3e704/download/walk-dublin-poi-details-sample-datap20130415-1449.json)

Write code to allow a user to filter countries by region, as shown here. Use the dataset from this link, which is copied from the dataset at https://restcountries.eu/rest/v2).

Adjust the countries in region example above, to allow the user to click on the "Country" or "Capital City" title so as to sort by country or by capital city, as shown here.

When using external JSON files, we can encounter JSON data that is stored in a tabular format (as discussed in the notes on JSON here), where the keys are separated from the values. For large datasets, this can significantly reduce the JSON file size. The JSON file in the example below separates the keys from the values.
Write code to display a table of disabled car parking spots in Dublin, as shown here. Use the dataset from this link, which is copied from the dataset at https://data.smartdublin.ie/datastore/dump/f2bf7e65-a75d-4252-b55e-7c786465262d?format=json).

Adjust the code from the above example to allow the user to search for a disabled car parking spot, as shown here. The search should:

 

 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>