Advertisements
<!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
>Solution :
it might be better to use $.append
instead of appenChild
<!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">
<tbody></tbody>
</table>
<script>
async function load(){
let json = await(
await fetch("https://gorest.co.in/public/v2/users")
).json()
show(json)
}
function show(data){
for(let i=0; i< data.length; i++){
let obj = data[i];
$('#table tbody').append(`
<tr>
<td> ${obj.name} </td>
<td> ${obj.email} </td>
</tr>
`)
}
};load()
</script>
</body>
</html>