37.3. Enhancing Your Page with AJaX

According to Jeremy Keith, [Kei10a], the term AJaX, an acronym for Asynchronous JavaScript and XML, was coined in 2005 by Jesse James Garrett. Ajax is a technology that allows sending messages from the JavaScript of your page to a server in order to retrieve information and subsequently add this information to your page.

The news in this is that you do not have to send a server request for a new page to get new information. You may update the info of the current page. This was not possible before. It obviously saves network bandwidth, and it adds intelligence to your page. It becomes adaptive. It is no longer static, but instead dynamically adapts to your interaction with it.

Important AJaX material is found at https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest. It is stated:

To send an HTTP request, create an XMLHttpRequest object, denominate a callback function, open a URL, and send the request.

This is exactly what we do in the following examples. The MDN example is terse, from the above link:

Example 37.1. First AJaX Example, ajaxfirst.js
'use strict';

const reqListener = function() {
    console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://x15.dk/about.html");
oReq.send();

Example 37.2. First AJaX Example Embedding, ajaxfirst.html
<!doctype html>
<html>
    <head>
        <title>NMLs AJaX First</title>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <script src='./ajaxfirst.js'></script>
    </head>
    <body>
        <h1>AJaX First</h1>
    </body>
</html>

Click here!


The first 'A' in AJaX is for asynchroneous. This means your code does not wait for the answer, but when the answer to your request. the response, arrives, there must be a designated function to deal with the response. This function is called the callback function.

The load is an eventlistener triggering when the page has loaded the response from the server. reqListener is the callback function that must be present somewhere in your code. To see proof of the asynchronousity look at

Example 37.3. Second AJaX Example, ajaxsecond.js
'use strict';

const reqListener = function() {
    console.log(this.responseText);
}

const init = function() {
    var oReq = new XMLHttpRequest();
    oReq.addEventListener("load", reqListener);
    oReq.open("GET", "http://x15.dk/about.html");
    oReq.send();
}

window.addEventListener('load', init);
console.log("The page is loaded! We're ready");

Example 37.4. Asynchroneous? ajaxsecond.html
<!doctype html>
<html>
    <head>
        <title>NMLs AJaX Second</title>
        <meta charset='utf-8'/>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <script src='./ajaxsecond.js'></script>
    </head>
    <body>
        <h1>AJaX Second</h1>
    </body>
</html>

Click here!


37.3.1. The Machine Room, XMLHttpRequest

In the following you will see xamples of AJaX getting plain text, XML, or JSON data, depending on our context, from a server. The AJaX calls in the examples are initiated by clicking buttons, and invoked through event listeners on those buttons. In order to ficilitate daily use we have create an object:

Example 37.5. The AJaX Object from XMLHttpRequest in ajax.js
'use strict';
/*
 * @author NML
 * @Date Apr 2020
 */

/*
 * method: AJaX:  getFileAjax
 * @param filename: url of wanted file
 * @param callback: function to handle response
 */
const getFileAjax = function (url) {
    let promObj = new Promise(function (resolve, reject) {
        const ajax = new XMLHttpRequest();
        ajax.open('GET', url);
        ajax.send();
        ajax.addEventListener('load', function (ev) {
            if (! ev) {
                reject(ajax.status);
                console.error("ajax failed");
            }
            console.log("ajax done successfully");
            var resp = ajax.responseXML;
            resolve(resp);
        });
        console.log("request sent succesfully");
    });
    return promObj;
}

export {getFileAjax};