• 20 hours
  • Easy

Free online content available in this course.

course.header.alt.is_certifying

Got it!

Last updated on 8/5/19

Extend your AJAX request

Log in or subscribe for free to enjoy all this course has to offer!

Instead of getting contents just from another HTML file, AJAX is often used to retrieve data in the form of JSON.

JSON stands for JavaScript Object Notation and is simply a way of structuring data. Many data sets you might retrieve from within your web application -- sometimes even data from a different website, like a weather service or a social network -- are in JSON. It's important to know how to handle received JSON via JavaScript.

Basic JSON syntax

In JSON, a list of candies with a name, brand, and quantity available for each one would look like this:

[
    {
        "name": "Gummy bears",
        "brand": "Haribo",
        "quantity": 5
    },
    {
        "name": "Chocolate bar",
        "brand": "Hershey's",
        "quantity": 3
    },
    {
        "name": "Licorice",
        "brand": "Twizzlers",
        "quantity": 4
    },
    {
        "name": "Truffles",
        "brand": "Godiva",
        "quantity": 0
    }
]

Open and close the JSON with square brackets, like any other array. Within each set of curly brackets, you have individual objects. Each of the above objects has properties called name,brand, andquantity.

You’ll notice in your project files for the course that you have a new file format ending in .json. You can place JSON within files ending in this format, and they’ll be read in the same way that external files from other websites would be read (say, if you were accessing photo data from Instagram).

Integrate JSON

The above contents will be in candies.json (or to a separate pen on CodePen, like so). Let's use AJAX now to request this data in the form of JSON, instead of HTML!

Candy shop

This chapter example involves a candy shop storefront (yum). We keep the candy inventory in candies.json, which lets us know how many candies of a particular kind there are in stock. On the storefront homepage, we want to display the candies, their names, and the quantity available.

You’ve already added the above JSON to candies. How can you access this JSON from within a JavaScript file though?

The first step is always to create a new XMLHttpRequest object. You can assign it to a variable calledreq.

You also want that request to get the contents of candies.json, since that's where your candies live! The actual code isn't too far off from the English. Use a GET request to grab the file's contents.

var req = new XMLHttpRequest();
req.open('GET', '/candies.json');

As seen in the previous chapter, you now have to check the state of the request via itsonreadystatechange property. Now it's time for the most fun part of the AJAX request: setting up that callback function!

Here's what should happen in our example.

1. Transform the JSON (basically a giant string) into a JavaScript object.
2. Create a list to hold the candies.
3. Create a list item for each candy.
   3a. If the candy has a quantity greater than 0, mark it as available.
   3b. If the candy has a quantity less than 0, mark it as sold out.
4. Add a non-functional "Buy" button just for appearances.
5. Insert that new HTML into our page.

1. Transform the JSON into a JavaScript object

There's a special method called JSON.parse() which takes JSON and returns it as a JavaScript object. In this case, we want to parse the request's response text and assign it to a variable called candies. We want an array of candies that we can individually work with in JavaScript, and that's exactly what we'll get back.

var candies = JSON.parse(req.responseText);
2. Create a list to hold the candies

This is as simple as writing HTML! Create a <ul>  with a class of candies and assign it to a variable called candyList, making it easy to reference in your JavaScript.

var candies = JSON.parse(req.responseText);
var candyList = '<ul class="candies">';
3. Create a list item for each candy and add a class depending on item's quantity

Loop time! Our for loop will run once for each item in the candies array starting with an index of 0 (the first candy). For each candy, an <li> will be created with a class of item. If the item has some stock left (quantity > 0), it'll also have the available class. If not, it will have a sold-out class. This lets you set different visual styles for sold out items.

Each candy's name and brand will be printed within its newli. Each li is added to the ul viacandyList +=.

for (var i=0; i<candies.length; i += 1) {
    if (candies[i].quantity > 0) {
        candyList += '<li class="item available">';
    } else {
        candyList += '<li class="item sold-out">';
    }
    candyList += candies[i].name + '<br>' + "Brand: " + candies[i].brand;
// ...
4. Add a non-functional Buy button just for appearances.

More easy HTML! Since you're still "within" the li tag, you'll add an HTML button for each candy to our growing candyList variable (at this point, a giant chunk of HTML).  

candyList += '<button>Buy</button>'

Now that you've written everything you want shown for each candy, you can close up that for loop as well as the li tag. 

    candyList += '</li>';
}

Once you're outside of the loop, you can also close the ul  tag. This means the loop will have run as many times as necessary, and all the lis  will have been created.

candyList += '</ul>';
5. Insert that new HTML into your page

Now you have a big chunk of HTML which you have generated line by line in JavaScript. To insert it into your actual page HTML, you'll use the getElementById method and grab the element with thecandyListing ID. It's a special div we created at the bottom of index.html (originally empty but soon to be manually filled with our new HTML) via the innerHTML property.

document.getElementById('candyListing').innerHTML = candyList;

Candy totality

Phew! All those steps got us here:

var req = new XMLHttpRequest();
req.open('GET', '/candies.json');
req.onreadystatechange = function () {
    if(req.readyState === 4 && req.status === 200) {
        var candies = JSON.parse(req.responseText);
        var candyList = '<ul class="candies">';
        for (var i=0; i<candies.length; i += 1) {
            if (candies[i].quantity > 0) {
            candyList += '<li class="item available">';
            } else {
            candyList += '<li class="item sold-out">';
        }
        candyList += candies[i].name + '<br>' + "Brand: " + candies[i].brand;
        candyList += '<button>Buy</button>'
        candyList += '</li>';
    }
    candyList += '</ul>';
    document.getElementById('candyListing').innerHTML = candyList;
    }
};
req.send();

Add that content to candies.js and open the HTML document using the web server you set up last chapter.

Candy list loaded via JSON
Candy list loaded via JSON

Here's the CodePen link to try the same example! Instead of linking to a JSON file directly, I put the candy list in the JS contents of another pen and linked to that pen: http://codepen.io/eclairereese/pen/QEKMdG 

Example of certificate of achievement
Example of certificate of achievement