Fetch data stored in a json file with JavaScript
Updated: 25-Jan-2023 / Tags: Javascript and JSON / Views: 5262 - Author: George
Introduction
Many times in our applications we need to fetch data from a JSON file and display them on the
screen. We can choose to use a server-side language like PHP to do the job, but most of the times
we are going use Ajax and Javascript. Actually, Ajax is javascript.
In this tutorial we are going to fetch some products that we have stored in a JSON file, and we are going to display
them in a responsive HTML template. Click on the "live demo button" to see the result.
Project's folder
In the image below we see how our project is structured.
- Lets walk through the projects folder and see all the files that we have there.
- Inside the root folder we have a products/ folder in which we have the image of every product that is stored in the JSON file.
- Next we have an index.html file. This is our home page. This is where the products will be displayed.
-
Next we have the products.json file. This is the file where the products are stored in a JSON format.
You will see the file in the next section. - Next we have a Javascript file. This is where we write our Javascript code.
- And last we have a styles.css stylesheet. In this file we have our css rules to make the content responsive.
The JSON file
Here we have the products.json file. Inside the file we have an array [] of objects.
Every object is a product, and every product has properties. There is an image, a title, a description, and a price property. We are gonna target those properties from the javascript file to display
each value.
[
{
"image": "products/01.jpg",
"title": "Product title",
"description": "Lorem ipsum dolor sit amet consectetur.",
"price": "9,99"
},
{
"image": "products/02.jpg",
"title": "Product title",
"description": "Lorem ipsum dolor sit amet consectetur.",
"price": "9,99"
},
{
"image": "products/03.jpg",
"title": "Product title",
"description": "Lorem ipsum dolor sit amet consectetur.",
"price": "9,99"
},
{
"image": "products/04.jpg",
"title": "Product title",
"description": "Lorem ipsum dolor sit amet consectetur.",
"price": "9,99"
},
{
"image": "products/05.jpg",
"title": "Product title",
"description": "Lorem ipsum dolor sit amet consectetur.",
"price": "9,99"
},
{
"image": "products/06.jpg",
"title": "Product title",
"description": "Lorem ipsum dolor sit amet consectetur.",
"price": "9,99"
}
]
The index file
Inside the body tags we need only one element, for our application and that is a div container
with a class of products. We give a class to the div element so we can target it from the javascript file.
And of course on line 3, we have a script tag that links the index file with the javascript file.
<body>
<div class="products"></div>
<script src="script.js"></script> <!-- link to the javascript file -->
</body>
The JavaSript file
Here we have the javascript file, and the code that will fetch the data from the JSON file. In short, we are going to send an xml-http-request to the server to get the JSON file. Then we are going to convert the JSON data to an array of objects. Then we are going to loop through the array and display every object in an html template.
let http = new XMLHttpRequest();
http.open('get', 'products.json', true);
http.send();
http.onload = function(){
if(this.readyState == 4 && this.status == 200){
let products = JSON.parse(this.responseText);
let output = "";
for(let item of products){
output += `
<div class="product">
<img src="${item.image}" alt="${item.description}">
<p class="title">${item.title}</p>
<p class="description">${item.description}</p>
<p class="price">
<span>${item.price}</span>
<span>€</span>
</p>
<p class="cart">Add to cart <i class="bx bx-cart-alt"></i></p>
</div>
`;
}
document.querySelector(".products").innerHTML = output;
}
}
Code breakdown
-
First i create a new xmlhttp-request object, in line 1.
The variable http holds now all methods and properties of the object.let http = new XMLHttpRequest();
-
Next i prepare the request with the open() method.
http.open('get', 'products.json', true);
The first argument sets the http method, here we use the GET method.
In the second argument we pass the file we want to fetch. In our case its the products.json file.
And last the keyword true, sets the request to be async. -
Next i will execute the request with the send() function. We don't use any parameters with the send() function
because this is a simple get request. We only want from the server to gives us the products.json file.
http.send();
-
Next we have to catch the servers response. The XMLHttpRequest object has a property called onload.
The onload property is fired when the transaction with the server is completed. We set the onload
property equal to a function, so when the onload property is fired the function is executed.
http.onload = function(){
-
Inside the function we check the readyState and the status property. To have a successful server response
their values must be 4, and 200.
if(this.readyState == 4 && this.status == 200){
-
The responseText property is holding the data from the server response.
But we can not use raw json data , we have to convert them to a javascript object so we can handle them. This is done with the JSON.parse() method.
Now the products variable is holding an array of objects.let products = JSON.parse(this.responseText);
-
Next i need an empty variable so i can add the incoming data.
let output = "";
-
Now i have to loop trough the products, and in every iteration
i will add a template literal (by using backtics ``, instead of quotes) to the output variable.
When we use this syntax ${item.image} we can add javascript values in a template literal.for(let item of products){ output += ` <div class="product"> <img src="${item.image}"> <p class="title">${item.title}</p> <p class="description">${item.description}</p> <p class="price"> <span>${item.price}</span> <span>€</span> </p> <p class="cart">Add to cart <i class="bx bx-cart-alt"></i></p> </div> `; }
-
And last i will target the products container and add the data that the output variable holds.
document.querySelector(".products").innerHTML = output; } // closing the if statement. } // closing the onload property.
And that is all the javascript code we need.
The CSS file
Here we have the css file. There is no need for me to explain any css rules, everything is straight forward.
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
font-family: 'Montserrat', sans-serif;
min-height: 100vh;
color: #555;
}
h2{
text-align: center;
margin-top: 50px;
font-size: 30px;
}
.products{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(350px, auto));
grid-gap: 50px;
margin: 50px auto;
max-width: 1240px;
padding: 20px;
}
.product{
padding: 10px;
box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
}
.product img{
width: 100%;
display: block;
}
.product .title{
text-align: center;
padding-top: 30px;
padding-bottom: 20px;
font-weight: 600;
text-transform: uppercase;
}
.product .description{
padding: 0 20px 20px 20px;
line-height: 22px;
}
.product .price{
text-align: center;
font-weight: 600;
font-size: 28px;
color: #9b0b03;
padding-top: 30px;
font-family: sans-serif;
text-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
transform: rotate(-45deg);
}
.product .cart{
text-align: center;
padding: 15px 0;
margin-top: 40px;
background-color: #3e628f;
color: white;
font-size: 18px;
cursor: pointer;
}
.product .cart i{
padding-left: 10px;
}
.view-more{
margin: 0 auto;
max-width: 1240px;
padding: 20px;
text-align: center;
}
.view-more button{
padding: 10px 25px;
}
Summary
We saw how to write an XMLHttp request to fetch data from a JSON file using Javascript and Ajax.
Last Words
Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.
Source code
You can download the source code and use it in any way you like.
Times downloaded: 1250
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉