JavaScript: Intro to AJAX

AJAX stands for Asynchronous JavaScript And XML. The basic concept is to use JavaScript and combine the fetching of XML (or JSON) data and make that data appear in some location of a web page without the page ever having been refreshed. This allows for dynamic content in an otherwise static page.

w3schools.com describes it like this:

AJAX is a developer’s dream, because you can:

  • Update a web page without reloading the page
  • Request data from a server – after the page has loaded
  • Receive data from a server – after the page has loaded
  • Send data to a server – in the background

For this intro, I followed along with the video tutorial produced by Brad Schiff on the Youtube channel LearnWebCode. I coded along with the video using the Atom IDE.

This tutorial details how to use the XMLHttpRequest() function to request JSON data, getElementById() to insert the data into the web page, and some logic for iteration, error handling, and JSON parsing. Here is the complete JavaScript code:

// Global variables
var pageCounter = 1;
var btn = document.getElementById('btn');
var animalContainer = document.getElementById('animal-info');

btn.addEventListener("click", function() {

    var ourRequest = new XMLHttpRequest();
    ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-' + pageCounter + '.json');
    ourRequest.onload = function() {

        // Add request error handling
        if (ourRequest.status >= 200 && ourRequest.status < 400) {
            var ourData = JSON.parse(ourRequest.responseText);
            renderHTML(ourData);
        }
        else {
            console.log("We connected to the server, but it returned an error.")
        }
    };

    // Error handling for bad connections
    ourRequest.onerror = function() {
        console.log("Connection error");
    };

    ourRequest.send();
    pageCounter++;
    // code to hide the button after 3 clicks
    if (pageCounter > 3) {
        btn.classList.add("hide-me");
    }
});

function renderHTML(data) {
    var htmlString = "";
    for (i = 0; i < data.length; i++) {

        htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat "

        // Loop through all liked foods
        for (ii = 0; ii < data[i].foods.likes.length; ii++) {
            if (ii == 0) {
                htmlString += data[i].foods.likes[ii];
            }
            else {
                htmlString += " and " + data[i].foods.likes[ii];
            }
        }

        htmlString += " and dislikes ";

        // Loop through all disliked foods
        for (j = 0; j < data[i].foods.dislikes.length; j++) {
            if (j == 0) {
                htmlString += data[i].foods.dislikes[j];
            }
            else {
                htmlString += " and " + data[i].foods.dislikes[j];
            }
        }
        htmlString +=  ".</p>";
    }
    animalContainer.insertAdjacentHTML('beforeend', htmlString);
};

Here is what the final page looks like, loaded in an iframe. With each click of the “Fetch info for 3 new animals” button, the information for three new animals is added to the page using AJAX, read from JSON data stored on the web. The button will disappear after the third click.

 

The JSON data can be found at these locations:
https://learnwebcode.github.io/json-example/animals-1.json
https://learnwebcode.github.io/json-example/animals-2.json
https://learnwebcode.github.io/json-example/animals-3.json

and looks like this:

[
  {
    "name": "Meowsy",
    "species" : "cat",
    "foods": {
      "likes": ["tuna", "catnip"],
      "dislikes": ["ham", "zucchini"]
    }
  },
  {
    "name": "Barky",
    "species" : "dog",
    "foods": {
      "likes": ["bones", "carrots"],
      "dislikes": ["tuna"]
    }
  },
  {
    "name": "Purrpaws",
    "species" : "cat",
    "foods": {
      "likes": ["mice"],
      "dislikes": ["cookies"]
    }
  }
]

Interesting concepts:


1.  Fetching data with XMLHttpRequest():

a) Set up a request variable:

var ourRequest = new XMLHttpRequest();

b) Use open() with GET and the URL to the data as arguments:

ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');

c) Get response text ourRequest.responseText and parse the JSON in one step using JSON.parse(data):

var ourData = JSON.parse(ourRequest.responseText);

d) Send the request:

ourRequest.send();

2. Use getElementById() to update web page location:

a) Create variable to hold the data:

var animalContainer = document.getElementById('animal-info');

b) Make a div id container in the HTML document:

<div id="animal-info">

c) Use insertAdjacentHTML() to insert the data into the HTML div container:

animalContainer.insertAdjacentHTML('beforeend', htmlString);

For more information about the insertAdjacentHTML() function, see:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML


3. Code to hide button (or other HTML element) via CSS update by adding a classList to the CSS element.

a) Add code like this to the JavaScript:

// code to hide the button after 3 clicks
if (pageCounter > 3) {
    btn.classList.add("hide-me");
}

b) “hide-me” is defined in the CSS file using visibility: hidden;

.hide-me {
  visibility: hidden;
  opacity: 0;
  transform: scale(.75);
}

4. Use of addEventListener()

a) addEventListener() is applied to the btn variable:

btn.addEventListener("click", function() { ... } );

which is tied to the button in the HTML:

var btn = document.getElementById('btn');
<button id="btn">Fetch info for 3 new animals</button>

b) addEventListener() takes two arguments. The first one is “click” and the second is a function definition.

“click” is an event. See:
https://developer.mozilla.org/en-US/docs/Web/Events/click

For more information about this function see:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

For more information about AJAX, see:
https://www.w3schools.com/js/js_ajax_intro.asp

Leave a Reply