AJAX (XHR vs. Fetch API)

AJAX
– stands for “Asynchronous JavaScript and XML”
– allows asynchronous communications with the server
– is used to update web pages without reloading them

(It’s normally also called AJAX if not used with XML.)


Example (with XHR and Fetch API)

<!DOCTYPE html>
<html>
    <head>
        <script src='https://code.jquery.com/jquery-latest.js' defer></script>
        <script src='countries.js' defer></script>
    </head>
    <body>
        <div>
            <select id='variantSel'>
                <option value='xhr1' label='via xhr (direct)'></option>
                <option value='xhr2' label='via xhr (jQuery)'></option>
                <option value='fetch1' label='via fetch (default)'></option>
                <option value='fetch2' label='via fetch (async/await)'></option>
            </select>
            <button id='requestBtn'>Load countries (EU)</button>
        </div>
        <div id='contentDiv'>
        </div>
    <body>
</html>
const requestBtn = document.getElementById('requestBtn');
const contentDiv = document.getElementById('contentDiv');

requestBtn.onclick = loadCountries;

function loadCountries() {
    contentDiv.innerHTML = '';

    const requestURL = 'https://restcountries.com/v3.1/subregion/europe';
    const variantSel = document.getElementById('variantSel');
    const currentVal = variantSel[variantSel.selectedIndex].value;

    switch (currentVal) {
        case 'xhr1':
            getWithXhr1(requestURL, writeCountries);
            break;
        case 'xhr2':
            getWithXhr2(requestURL, writeCountries);
            break;
        case 'fetch1':
            getWithFetch1(requestURL, writeCountries);
            break;
        case 'fetch2':
            getWithFetch2(requestURL, writeCountries);
            break;
    }
}

function getWithXhr1(requestURL, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', requestURL);
    xhr.responseType = 'json';
    xhr.onload = function() {
        callback(xhr.response);
    };
    xhr.send();
}

function getWithXhr2(requestURL, callback) {
    $.ajax({
        url: requestURL,
        dataType: 'json',
        success: function(data) {
            callback(data);
        }
    });
}

function getWithFetch1(requestURL, callback) {
    fetch(requestURL)
    .then(function(httpResponse) {
        return httpResponse.json();
    })
    .then(function(jsonContent) {
        callback(jsonContent);
    });
}

async function getWithFetch2(requestURL, callback) {
    const httpResponse = await fetch(requestURL);
    const jsonContent = await httpResponse.json();
    writeCountries(jsonContent);
}

function writeCountries(countries) {
    countries.forEach(function(country) {
        const countryDiv = document.createElement('div');
        countryDiv.innerHTML = country.name.common;
        contentDiv.appendChild(countryDiv);
    });
}

Comparison

XHR Fetch API
– Old school
– Works with Callbacks
– New school
– Works with Promises