AJAX

AJAX (Asynchronous JavaScript + XML) allow webpages to send data to another webpage and to retrieve data from a data source - such as a JSON file or a database - asynchronously (in the background) without interfering with the display and behavior of the existing page.

Using AJAX, a webpage can change its content in real-time. By using AJAX, we do not have to load a new webpage. Instead, we can update the current webpage based on new data that we read from the data source.

AJAX webpages 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 hold the data that is being sent using AJAX.

IMPORTANT: If we store a JSON object in an external file, then we need to put " quotes around each property key and value (including numerical values), 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>
async function ajaxListAllCars()
{
    let url = `car_details.json`      /* name of the JSON file */

    try
    {
        const response = await fetch(url,
        {
            method: `POST`,
            headers: {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        })

        updateWebpage(await response.json())
    }
    catch (error)
    {
        console.log('Fetch failed: ', error)
    }


    /* use the fetched data to change the content of the webpage */
    function updateWebpage(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 onload='ajaxListAllCars()'>

<div id = 'cars'>Car details will be listed here.</div>

</body>
</html>

In the above example, the AJAX function is called when the webpage loads, as shown below:

<body onload='ajaxListAllCars()'>

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

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

AJAX functions are asynchronous. This means that the webpage does not wait for the function to return a value. Instead, the function is called in the background and the website continues to behave as it did before the AJAX function call was made. Once the AJAX function retrieves the JSON data, it calls another function within the webpage. This function is used to update the webpage with the JSON data. Using AJAX makes sense, because the data source file might be very big. If the loading of the data did not happen in the background, then the webpage could freeze.

Asynchronous (ie AJAX) functions have the keyword async placed in fron of them, as shown below:

async function ajaxListAllCars()
{
    ...

The parameter of the function that will be called when the JSON data has been retrieved has the keyword await placed in front of it. The await keyword forces this function to wait until the JSON data has been loaded from the data source. In the code below, the function updateWebpage will be called after the JSON data has been loaded.

        updateWebpage(await response.json())

When the function updateWebpage is called, it parameter will be the JSON data (i.e. the result of response.json() from the line of code above). Therefore, jsonData will contain the JSON data from the source file.

    function updateWebpage(jsonData)
    {
        ...

The updateWebpage function is used to to change the content of a webpage.

Firstly, we construct a HTML string. In this example, we use the variable htmlString to hold the string. From the code below, htmlString will contain a <TABLE> element that contains one row for each car.

        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.`

Secondly, once we have constructed the HTML string, we insert it into a <DIV> element. This is done using the code below.

        document.getElementById('cars').innerHTML = htmlString

In order for the above code to work, we need to have a <DIV> element named cars in the HTML code on the webpage, as shown below.

<div id = 'cars'>Car details will be listed here.</div>

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

Coding your own AJAX Functions

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

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

    try
    {
        const response = await fetch(url,
        {
            method: `POST`,
            headers: {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        })

        updateWebpage(await response.json())
    }
    catch (error)
    {
        console.log('Fetch failed: ', error)
    }


    /* use the fetched data to change the content of the webpage */
    function updateWebpage(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 onload='ajaxListAllCars()'>

<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 AJAX to access these.

Write code to display a table of attractions to see in Dublin, as shown here. Use the dataset from this link, which is copied from 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>