Skip to content

J140 Use of AJAX

A task focusing on AJAX operations in JavaScript to fetch and display data from an external source.

Objective: To understand AJAX operations, specifically using the fetch function in modern JavaScript. You will retrieve a list of regions from the DAWA and display these in a list.

Setup: From the URL https://dawa.aws.dk/landsdele/, a JSON structure similar to the provided example is returned. This consists of an array of objects. You need to create a list with the region’s code (nuts3) and name (DK014 Bornholm ...).

You can use the provided HTML as a starting point:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AJAX</title>
  </head>
  <body>
    <button id="knap">Click me</button>
    <ul id="lst"></ul>
    <script src="app.js"></script>
  </body>
</html>

And the provided JS structure:

(async function(){

// code

})();

When the button is clicked, the data should be fetched and displayed. You can use the fetch method for this task. Remember, to use await, it should be within an async method. The fetch method returns a request, and you can get the JSON data by calling the json method on it, which also requires await.

Tip

  • When using fetch, ensure you handle both the success and error cases.
  • The onClick method of the button should be an async function.
Solution
(async function(){

    // Selecting the button and list element
    let button = document.getElementById('knap');
    let list = document.getElementById('lst');

    button.onclick = async function() {
        try {
            // Fetching the data from the API
            let response = await fetch('https://dawa.aws.dk/landsdele/');

            // Checking if the fetch was successful
            if(!response.ok) {
                throw new Error('Network response was not ok');
            }

            // Parsing the JSON data
            let data = await response.json();

            // Clearing the previous list
            list.innerHTML = '';

            // Looping through the data to append to the list
            data.forEach(item => {
                let listItem = document.createElement('li');
                listItem.textContent = `${item.nuts3} ${item.navn}`;
                list.appendChild(listItem);
            });

        } catch (error) {
            console.error('Fetch operation failed: ', error);
        }
    }

})();

When this solution is combined with the provided HTML, clicking on the button will fetch the data and populate the list with the regions’ code and name.