<!DOCTYPE html>
<html>
<head>
<title>Fetch data from API and display in table using AJAX</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Data</h1>
<table id="table" border="1"></table>
<script>
function load(){
fetch("https://gorest.co.in/public/v2/users")
.then(result => result.json)
.then(json => show(json)) }
function show(data){
let table = document.getElementById('table');
for(let i=0; i< data.length; i++){
let obj = data[i];
console.log(obj);
let row = document.createElement('tr');
let name = document. createElement('td');
id.innerHTML = obj.
row.appendChild(name)
table.appendChild(row)
}
}
</script>
</body>
</html>
I need to fetch data from a url. I have to present it in a table. First I only need to display username with a button "view more". When view more will be clicked I have to fetch data from another api related to that particular username .I have written few line of code but they are not working. Any suggestionns? your text
3
Answers
it might be better to use
$.append
instead ofappenChild
Here is a simpler plain JavaScript version
You need to call .json() to get the object
I am only guessing what you meant with "show more" but here is a working script
As per your request i fetched the data from api in the
load()
fucntion and then displayed it in table form usingshow()
function.I have kept a
global
boolean variableisMore
to show more details fetched from api when clicked onShow More
button
.There i added a dynamic button and when it is clicked then
showMore()
function is called.This function changes the value of boolean variable
isMore
totrue
and then calls theload()
function again.This
load()
function inturn calls theshow()
function by passing the data and there i check the condition for booleanisMore
if it istrue
then i show more details as per your need..