In this blog post, we will learn how to fetch data from an API and display it in tabular format.
Setting Up the HTML Structure
The below HTML code represents a simple web page designed to display data in a table format. It includes a button labeled "Load Data" that, when clicked, will dynamically populate the table with data using JavaScript.
The structure consists of a <table> element with a <thead> for column headers (Id, Name, and Email) and an empty <tbody> where the data will be loaded. External files, style.css and app.js, are linked for styling and scripting, respectively, allowing for separation of concerns.
This setup is ideal for implementing interactive data-loading features, such as fetching information from an API and rendering it in a clean, tabular format.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id='submitdata'>
Load Data
</button>
<br>
<table id='datatable'>
<thead>
<tr>
<th> Id </th>
<th> Name </th>
<th> Email </th>
</tr>
</thead>
<tbody>
<! -- Data will be loaded here -->
</tbody>
</table>
</body>
<script src="app.js"></script>
</html>
The Javascript Code
To complement the HTML structure, the below JavaScript code sets up an event listener for a button with the ID `submitdata`, which, when clicked, triggers the `fetchData` function to retrieve user data from an external API.
Initially, the code logs the button element to the console for verification. The `fetchData` function constructs a URL pointing to the JSONPlaceholder API, specifically targeting user data. It uses the Fetch API to send a GET request to this URL and processes the response by converting it into JSON format.
If successful, it calls the `displayDataInTable` function, passing the retrieved data as an argument. This function dynamically creates table rows for each user in the data array, extracting and appending the user's ID, name, and email into corresponding table cells (`<td>` elements).
Finally, these rows are appended to the table body of an HTML table identified by `#datatable`, effectively displaying the fetched user information in a structured format on the webpage. If any errors occur during the fetch operation, they are logged to the console with an error message.
const loadData = document.getElementById('submitdata')
console.log(loadData);
loadData.addEventListener('click', fetchData);
function fetchData() {
console.log('data is fetching');
const apiUrl = 'https://jsonplaceholder.typicode.com/users';
fetch(apiUrl)
.then(response => response.json())
.then(data => displayDataInTable(data))
.catch(err => console.error('error fetching data..',err));
}
function displayDataInTable(data){
const tbod = document.querySelector('#datatable tbody');
data.forEach(user =>{
const row = document.createElement('tr');
const id = document.createElement('td');
id.textContent = user.id;
row.appendChild(id);
const name = document.createElement('td');
name.textContent = user.name;
row.appendChild(name);
const email = document.createElement('td');
email.textContent = user.email;
row.appendChild(email);
tbod.appendChild(row);
} );
}
Adding Some Styling
Below is the code for styling.
button {
/* Add your styles here */
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 8px;
text-align: left;
}
The final output will look like this:
If you click on Load Data button, the data is fetched from the endpoint and displayed in the table as shown below:
0 Comments