AJAX-SON 5

Beginner Asynchronous JavaScript And XML (JSON)

An important aspect of modern web development is being able to asynchronously update a web page with out having to refresh the browser. Imagine having to refresh the browser every time you want to see an update to your Twitter feed. Fortunately, at the top of Twitter page we can view the number of new messages without having to refresh the page. This sort of functionality is the idea behind using AJAX.

I think one of the (multiple) things that killed myspace was the inability to keep the user experience on a single page. For instance, if you wanted to check a new message in your inbox it was necessary to click a button that took the user to a new page. If you wanted to check a bulletin, a page refresh was needed. There was a lot of navigating throughout the site which made the user experience slow and unenjoyable. Along came Facebook where we could stay on one page to check messages, wall posts, and more. This was faster and convenient. Behind the scenes to this at Facebook was AJAX.

What is AJAX

The acronym stands for Asynchronous JavaScript and XML. However don’t be fooled by the XML part. In modern web development sending JSON files back and forth is more popular than the older XML format. However, both formats use the same technology to send the data. In our example below we’ll be using JSON along with an XMLHttpRequest, a function baked into the web API.

XMLHttpRequest

The XMLHttpRequest is a client that provides functionality for transferring data between a client and a server. In other words, if we feed this function an endpoint, it then provides an easy way to retrieve data without interrupting what the user is doing. The XMLHttpRequest can send and receive information in various formats, including JSON, XML, HTML, and text files. This is all done in the background while the user is on the page.

This is it vital for us to create our SPA (Single Page Application) just like Facebook. Another example to understand this is when Googling just about anything. Every time a new letter is typed the search starts to load differently. The importance of this is that there is no need to reload the web page upon a user event!

If you’d like to follow along, you can clone the repo at https://github.com/robhitt/intro-to-ajax-blog.

For this example we’re going to use the Spotify API and list the Jackson 5 album covers. The Spotify endpoint looks like this: https://api.spotify.com/v1/search?q=artist:ARTIST NAME&type=album, you can insert your own artist name too and give it a shot.

HTML

First thing is first, lets wire up our HTML page.

Header: 
<link type=”text/css” rel=”stylesheet” href=”./css/styles.css”>
End of Body:
<script type=”text/javascript” src=”./js/main.js”></script>

- Create an id called ‘btn’ that we’ll be using in our button tag which we’re going to add an event handler to. This event handler will be making the XMLHttpRequest to the spotify endpoint when a user clicks the button.

- Create an id called ‘album-cover’ — this is where we’ll be adding subsequent album covers to our page.

<button id="btn">Add Jackson 5 album cover</button>
<p id="album-cover"></p>

JAVASCRIPT

1. Grab button element and add a ‘click’ event listener. Notice that we’re going to call the addJackson function once the button is clicked.

var jacksonButton = document.getElementById(‘btn’);
jacksonButton.addEventListener(“click”, addJackson);

2. Grab the album covers element

var albumsContainer = document.getElementById(‘album-cover’);

3. Set the URL endpoint to include the artist “jackson 5” and also create a variable albumCount, this is how we will iterate through the JSON file we receive.

var url = “https://api.spotify.com/v1/search?q=artist:jackson 5&type=album”;
var albumCount = 0;

4. Here’s the heart of the file, the AJAX request.

- We first create a new instance of the XMLHttpRequest

- We open this request by including a GET request as the first parameter and the URL as the second. The open method takes a 3rd paramater which is true or false. Using true means it is using an async request and this is also the default.

- Assign an anonymous function to request.onload. This is where we load the JSON using the method responseText and then we convert the JSON file to an object with the JSON.parse method.

- Once JSON is parsed we call the renderJackson method which is where we create display the images to the webpage.

- Lastly we need to sendthe request.

function addJackson( ){
  var request = new XMLHttpRequest();
request.open(‘GET’, url);

request.onload = function(){
var jacksonData = JSON.parse(request.responseText);
renderJackson(jacksonData);
};
  request.send();
}

5. Here we dig down into our response Object that the Spotify API gave us so that we can grab the image url of the album cover.

- Start with an empty string called newAlbum.

- Grab the album URL of the current button click. We know we’re at the first album in the list because our global variable ‘albumCount’ was set to zero at the top of the file.

- In the Object, we have to dig 5 levels deep to grab the album image URL. data >> albums >> items[arrayIndex] >> images[arrayIndex] >> url

- Once we have the image url we add it to a new image tag one after another.

- Lastly we increment our albumCount so if the user chooses to add an additional album it will go to the following album that Spotify gave us in the JSON file.

function renderJackson(data){
var newAlbum = ‘’;
  var albumURL = data.albums.items[albumCount].images[0].url;
newAlbum += “<img src=’” + albumURL + “‘>”
  albumsContainer.insertAdjacentHTML(‘beforeend’, newAlbum);  
albumCount++;
}

And that’s it, Try it below! Let me know if you have any questions or sent me a pull request:

Jackson 5 on the web: https://robhitt.com/blog/intro-to-ajax/

Jackson 5 GitHub repo: https://github.com/robhitt/intro-to-ajax-blog

https://robhitt.com/blog/intro-to-ajax/