How to load JSON using Ajax in 9 easy steps with a fun project

In an attempt to brush up my JS skills for the coming year, I decided to build out a sample project.

Considering the political climate, I thought it would be fun to load all the presidents of America with details about their party, date of birth and death if applicable, year in office etc onto a webpage, on the click of a button.

GOAL:

A JSON file living on the server has the list of all the presidents and the extra details about each president. Create a webpage which has a button, on the click of which it fetches the JSON file from the server and displays the contents of the JSON file, below the button in a table.

Essentially, the contents of the JSON file are loaded on the fly. Which means when the page is loaded the first time, there is only empty div on the page and a button. When the button is clicked, using Javascript, the browser goes to the internet and downloads the information from the server onto the page and creates the HTML. All this happens without a page refresh.

Notes

  • JSON is used to send, store and receive data from the server.
  • JSON stands for Javascript Object Notation.
  • JSON is a array of objects.
  • For this project, I created a JSON file that I forked from github at the URL: https://github.com/hitch17/sample-data/blob/master/presidents.json
  • Ajax stands for Asynchronous Javascript and XML.
  • Ajax is the process of sending and receiving data on the fly without a page refresh.
  • Browser uses XMLHTTPRequest to establish a connection to a specified URL and send and receive data.

Step 1:

  • Create a button on the web page.
  • Create an empty div to load the contents of the JSON file.
<button id="get-details">Get Details of All American Presidents</button>
<div id="results"></div>

Step 2:

  • Create a new instance of XMLHttpRequest
  • Open a connection and specify if you are sending(POST) or receiving(GET) data using POST/GET and the URL where the JSON data file is located.
  • Specify what function or tasks to perform once the connection is LOADED.
  • Send the request to the server.
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://www.femkreations.com/projects/presidents-list-json-ajax/presidents.json');
ourRequest.onload = function(){
console.log(ourRequest.responseText);
};
ourRequest.send();
Screenshot of the console with JSON result

Notes

  • In Step 2, we logged the output of the JSON to the console, just to test that things are working well so far.
  • The XMLHttpRequest property – responseText is used to retrieve the text data received from the server once the request has been received.
  • The XMLHttpRequest property – statusText can be used to retrieve a string status message from the server.
  • The XMLHttpRequest property – status can be used to retrieve a numerical status code from the server.

Step 3:

  • Store the result of the JSON response into a variable.
  • The results are usually one big text string and NOT a JSON object. Using the browser filter JSON.parse, convert the text string into a JSON object.
  • Extract the first object from the array.
ourRequest.onload = function(){
var ourData= JSON.parse(ourRequest.responseText);
console.log(ourData[0]);
};
Screenshot of console with first JSON object

Step 4:

  • Add an event listener to the button’s click event so the AJAX is loaded on the button click.
var ourRequest = new XMLHttpRequest();
var ourButton = document.getElementById('get-details');
ourButton.addEventListener('click', function(){
ourRequest.open('GET', 'http://www.femkreations.com/projects/presidents-list-json-ajax/presidents.json');
ourRequest.onload = function(){
var ourData= JSON.parse(ourRequest.responseText);
console.log(ourData[0]);
};
ourRequest.send();
});

Step 5:

  • Build out the HTML on the page-to the empty div created in Step 1- from the JSON objects. As a proof of concept, create a test line in the empty div.
  • To keep things organized in the code, the code rendering JS is written in a separate function.
var ourRequest = new XMLHttpRequest();
var ourButton = document.getElementById('get-details');
var ourDiv = document.getElementById('results');
ourButton.addEventListener('click', function(){
ourRequest.open('GET', 'http://www.femkreations.com/projects/presidents-list-json-ajax/presidents.json');
ourRequest.onload = function(){
var ourData= JSON.parse(ourRequest.responseText);
renderHtml(ourData);
};
ourRequest.send();
});


function renderHtml(data){
ourDiv.insertAdjacentHTML('afterbegin', 'testing');
}
Screenshot of Empty Div
Screenshot of DIV with the Test HTML

Step 6:

  • Build out the actual HTML on the page-to the empty div created in Step 1- from the JSON objects.
  • Use the for-loop to loop through the array and display the objects in the array in a new paragraph tag.
function renderHtml(data){
var htmlString = '';
for (i=0;i< data.length;i++){
htmlString += '<p>' + data[i].number +  data[i].president  + data[i].birth_year  + data[i].death_year + data[i].took_office  + data[i].left_office + data[i].party + '</p>';
}
ourDiv.insertAdjacentHTML('afterbegin', htmlString);
}
Screenshot loading the JSON results into the HTML on the button click

Step 7:

  • Make the results look pretty by formatting the HTML in a table layout.
  • Add CSS to the table to enhance the table layout.
function renderHtml(data){
var htmlString = '';
htmlString += '<table><tr><th>No</th> <th>Name</th> <th>Birth</th> <th>Death</th> <th>Took Office</th> <th>Left Office</th> <th>Party</th> </tr>';
for (i=0;i< data.length;i++){
htmlString += '<tr>';
htmlString += '<td>'+ data[i].number + '</td>';
htmlString += '<td>'+ data[i].president + '</td>';
htmlString += '<td>'+ data[i].birth_year + '</td>';
htmlString += '<td>'+ data[i].death_year + '</td>';
htmlString += '<td>'+ data[i].took_office + '</td>';
htmlString += '<td>'+ data[i].left_office + '</td>';
htmlString += '<td>'+ data[i].party + '</td>';
htmlString += '</tr>';
}
htmlString += '</table>';
ourDiv.insertAdjacentHTML('beforebegin', htmlString);
}
table{
border-collapse: collapse;
width: 100%;
margin-top:20px;
}
table td, table th {
border: 1px solid #f9f1ed;
padding: 8px;
}
table tr:nth-child(even){background-color: #f8f5f1;}
table tr:hover {background-color: #f9f1ed;}
table th {
padding-top: 10px;
padding-bottom: 10px;
text-align: left;
background-color: #ed6b29;
color: white;
}
Screenshot of the list of presidents in a table layout
Screenshot of the table after adding some css

Step 8:

  • Add counter to make sure that once the button is clicked and the JSON is loaded into the Div, the button is disabled. Otherwise the table is loaded every time the button gets clicked.
  • Add CSS to the button for the enabled/disabled state.
var clickCounter = 0;
.
.
.
ourButton.addEventListener('click', function(){
.
.
.
clickCounter++;
if (clickCounter >= 1){
ourButton.setAttribute('disabled', 'disabled');
}
});
#get-details{
background-color:#443328;
padding:10px 15px;
font-size:1em;
font-weight:bold;
border-radius:5px;
color:white;
}
#get-details[disabled]{
opacity: 0.65;
cursor: not-allowed;
}
Screenshot of the button in enabled state
Screenshot of the button in disabled state once the table is loaded

Step 9:

  • Add error handling for the AJAX requests.
ourRequest.onload = function(){
if (ourRequest.status >=200 && ourRequest.status<400){
var ourData= JSON.parse(ourRequest.responseText);
renderHtml(ourData);
}
else {
console.log('We connected to the server but did not get a response');
}


};

ourRequest.onerror = function(){
console.log('Connection Error');
};

Notes

  • Using the property – onerror, we can check if there is a connection error. If so we can do something useful in the real world. In our example, we output an error message to the console.
  • Using the property – status, and checking if the status code is between 200 and 400, we can verify if we were successful in connecting to the server. A status code outside this range means the connection happened, but the server didn’t respond successfully. If so we can do something useful in the real world. In our example, we output an error message to the console.

Q for you: Did you run into any coding challenge when you worked on this fun project to load JSON using Ajax?
Leave a comment below and let me know.

Leave a Reply

Your email address will not be published. Required fields are marked *

Endorsed by these folks ...

Femy is an absolute joy to work with. She’s very knowledgeable as a front end developer and takes the time to make sure things are right the first time. Her work is very clean and professional and her attitude is great…all the time! She’ll take the time to help you even if she is already booked. Femy is a great asset to SolutionSet.

Jaime Lutz Project Manager, SolutionSet