How to get particular JSON Data into a table - javascript

I'm a total beginner, so I've been kinda of banging my head against a wall trying to figure this out.
Basically, the code below displays json data from a url and displays it in a table. At the moment all 12 keys in the object are being displayed in the table.
What I would like to know is how would I go about displaying just some of the keys in the table. For example, how would I build a table that just has short, long, price and volume being displayed.
I hope this makes sense, thanks in advance
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Using Coincap.io API</title>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container-fluid fill-page">
<div class="row justify-content-center align-items-center">
<div class="col-10">
<div class="waitingDiv text-center">loading...</div>
<table class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-dark"></thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
<script>
$(document).ready(function() {
$.ajax({
url: "https://coincap.io/front",
type: "GET",
dataType: "json"
}).done(function(data, textStatus, jqxhr) {
//only look at first 25 results...
data = data.slice(0, 10);
$.each(data, function(index, value) {
if (index == 0) {
$("thead").append("<tr id='tr-header'> ");
$.each(Object.keys(data[index]), function(propertyName, value){
$("#tr-header").append("<th>" + value + "</th>");
});
$("thead").append("</tr>");
}
$("tbody").append("<tr id='tr-" + index + "'> ");
$.each(data[index], function(propertyPosition, value){
$("#tr-" + index).append(
"<td>" + data[index][propertyPosition] + "</td>"
);
});
$("tbody").append("</tr>");
});
$('.waitingDiv').hide();
}).fail(function(jqxhr, textStatus, errorThrown){
console.log("failed");
});
});
<script>

You can check for if propertyName is in an array of keys that you want to show.
var keys_to_show = ["short", "long", "price", "volume"];
$.each(Object.keys(data[index]), function(propertyName, value) {
if (keys_to_show.includes(propertyName)) {
$("#tr-header").append("<th>" + value + "</th>");
}
});

Related

Why is my insertRow method adding blank cells to my table?

I am trying to add the results from a fetch request into a new row in a table. However, When I run the function to do that, the first click adds a blank row instead of adding my desired data. Additionally, the data that I would have liked to add gets added the next time the function is ran. I have no idea what is wrong and I have tried so many things. I believe this problem is causing my other function called "total()" to return an error as the first cell is undefined instead of containing a value.
Here is my javascript:
document.getElementById('getFood').addEventListener('click', getFood);
document.getElementById('getFood').addEventListener('click', total);
/*function getText() {
$.ajax({
method: 'GET',
url:
'https://api.api-ninjas.com/v1/nutrition?query=' +
document.getElementById('foodInput'),
headers: { 'X-Api-Key': 'vrtwcc/pVgAr2o/a4dEyYA==hR1m7lLVdU4ho4hW' },
contentType: 'application/json',
success: function (result) {
console.log(result);
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
},
});
}*/
/*function getFood(foodName) {
let xhr = new XMLHttpRequest();
xhr.open(
'get',
'https://api.api-ninjas.com/v1/nutrition?query=' + foodName,
true
);
xhr.send();
xhr.addEventListener('load', function () {
console.log(xhr.responseText);
});
}
getFood('fries');*/
function getFood() {
fetch(
'https://api.api-ninjas.com/v1/nutrition?query=' +
`${document.getElementById('foodInput').value}`,
{
method: 'GET',
headers: { 'X-Api-Key': 'vrtwcc/pVgAr2o/a4dEyYA==hR1m7lLVdU4ho4hW' },
contentType: 'application/json',
}
)
.then((res) => res.json())
.then((data) => {
foodQuery = data[0].name;
calorieQuery = `${data[0].calories} calories`;
});
let table = document
.getElementById('foodTable')
.getElementsByTagName('tbody')[0];
let row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = foodQuery;
cell2.innerHTML = calorieQuery;
// row.insertCell(0).innerHTML = foodQuery;
// row.insertCell(1).innerHTML = calorieQuery;
//document.getElementById('foodInput').value = '';
}
function total() {
let table = document.getElementById('foodTable');
let total = 0;
for (let i = 1; i < table.rows.length; i++) {
total += Number(table.rows[i].cells[2].innerText);
}
document.getElementById('tableTotal').value = total;
}
and here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.6.3.js"
integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM="
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="node_modules/bootstrap/dist/css/bootstrap.css"
/>
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="container-fluid border border-primary">
<strong>Jason's Calorie Counter </strong><br />
<form>
<div class="form-group" id="">
<label>Food Selection</label>
<input
class="form-control"
id="foodInput"
placeholder="Enter food here"
/>
<small id="foodHelp" class="form-text text-muted"
>Nutrition data for each food item is scaled to 100g unless a
quantity is specified
</small>
<br />
<button type="button" class="btn btn-primary" id="getFood">
Get Food
</button>
</div>
</form>
</div>
<table class="table table-bordered" id="foodTable">
<thead>
<tr>
<th scope="col">Food</th>
<th scope="col">Calories</th>
</tr>
</thead>
<tbody>
<tr id="rows1">
<td colspan="2" id="tableTotal">Total</td>
</tr>
</tbody>
</table>
<script
src="https://cdn.jsdelivr.net/npm/popper.js#1.14.7/dist/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"
></script>
<script src="script.js"></script>
</body>
</html>
One more important detail: The new row gets added correctly when just adding a string, so it may have to do with the variable or the fetch request. Thank you very much for your time and if there is more information that is missing, please tell me and I will do my best to add it.
I have tried changing the type of data being added, adding them to different parts of the table, changing syntax, etc..
total() is probably called before the number is populated. You should have it execute after the cell is populated and not on click.

JSON throw undefined in HTML

Please help me I am new in API integration
I want to show Poster, Title and year from API url.
here is the code which i tried, when i log, its shows JSON in array but its throw undefined in front end please help.
Thanks in advance
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>Welcome</title>
</head>
<body>
<div class="container">
<div class="table-responsive">
<h1>Movies</h1>
<table class="table table-bordered table-responsive table-striped" id="movies_table">
<tr>
<th>Poster</th>
<th>Name</th>
<th>Year</th>
</tr>
</table>
</div>
</div>
<div id="my_div" class="hide">"Thank You"</div>
</body>
<script>
$(document).ready(function(){
$.getJSON("http://www.omdbapi.com/?apikey=d8ecb486&s=red", function(data) {
console.log(data);
var movies = '';
$.each(data, function(key,value){
movies += '<tr>';
movies += '<td>'+value.poster+'</td>';
movies += '<td>'+value.title+'</td>';
movies += '<td>'+value.year+'</td>';
movies += '</tr>';
});
$('#movies_table').append(movies);
});
});
</script>
</html>
here is the API structure
{"Search":[{"Title":"RED","Year":"2010","imdbID":"tt1245526","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMzg2Mjg1OTk0NF5BMl5BanBnXkFtZTcwMjQ4MTA3Mw##._V1_SX300.jpg"},{"Title":"Red Dragon","Year":"2002","imdbID":"tt0289765","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTQ4MDgzNjM5MF5BMl5BanBnXkFtZTYwMjUwMzY2._V1_SX300.jpg"},{"Title":"The Hunt for Red October","Year":"1990","imdbID":"tt0099810","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BY2Y5NWVjMmQtMWRmOC00ZTg3LWI3YWQtZGI2MWUwNWQ4OWQ2XkEyXkFqcGdeQXVyNDk3NzU2MTQ#._V1_SX300.jpg"},{"Title":"The Thin Red Line","Year":"1998","imdbID":"tt0120863","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BYjEzMTM2NjAtNWFmZC00MTVlLTgyMmQtMGQyNTFjZDk5N2NmXkEyXkFqcGdeQXVyNzQ1ODk3MTQ#._V1_SX300.jpg"},{"Title":"RED 2","Year":"2013","imdbID":"tt1821694","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMjI2ODQ4ODY3Nl5BMl5BanBnXkFtZTcwNTc2NzE1OQ##._V1_SX300.jpg"},{"Title":"Red Sparrow","Year":"2018","imdbID":"tt2873282","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTA3MDkxOTc4NDdeQTJeQWpwZ15BbWU4MDAxNzgyNTQz._V1_SX300.jpg"},{"Title":"Red Eye","Year":"2005","imdbID":"tt0421239","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BNzAxNjc1ODczOF5BMl5BanBnXkFtZTcwMjE3MjEzMw##._V1_SX300.jpg"},{"Title":"Red Riding Hood","Year":"2011","imdbID":"tt1486185","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTc4NjYyMzQ5MV5BMl5BanBnXkFtZTcwNjE5Mjc3NA##._V1_SX300.jpg"},{"Title":"Three Colors: Red","Year":"1994","imdbID":"tt0111495","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BYTg1MmNiMjItMmY4Yy00ZDQ3LThjMzYtZGQ0ZTQzNTdkMGQ1L2ltYWdlL2ltYWdlXkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg"},{"Title":"Red Dawn","Year":"2012","imdbID":"tt1234719","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMjI0MDAwMzA1M15BMl5BanBnXkFtZTcwNzIxMjY3OA##._V1_SX300.jpg"}],"totalResults":"3993","Response":"True"}
there are multiple things
First of all your actual data is coming under Search Array
secondly the key you're trying to read is starting from Uppercase
then if you iterate through search array key will be index like 0,1,2...n and you need to read from value
just update this logic and you're good to go
var movies = '';
$.each(response.Search, function(key,value){
movies += `<tr>
<td>${value.Poster}</td>
<td>${value.Title}</td>
<td>${value.Year}</td>
</tr>`;
});
$('#movies_table').append(movies);
The issue is with your each loop, you need to use key.poster instead of value.poster. The first argumemnt to loop specifies the data element.
$(document).ready(function(){
$.getJSON("http://www.omdbapi.com/?apikey=d8ecb486&s=red", function(data) {
console.log(data);
var movies = '';
$.each(data, function(key,value){
movies += '<tr>';
movies += '<td>'+key.poster+'</td>';
movies += '<td>'+key.title+'</td>';
movies += '<td>'+key.year+'</td>';
movies += '</tr>';
});
$('#movies_table').append(movies);
});
});

How to convert this into DataTable?

I want to display this layout in 5 rows at a time type using DataTable
so, please help me with this.
I tried many things but I'm unable to do it.
<!DOCTYPE html>
<html>
<head>
<title>CSV File to HTML Table Using AJAX jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css"></style>
<script type="text/javascript" src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive">
<h1 align="center">CSV File to HTML Table Using AJAX jQuery</h1>
<br />
<div align="center">
<button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
</div>
<br />
<div id="employee_table">
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#load_data').click(function(){
$.ajax({
url:"iguana.csv",
dataType:"text",
success:function(data)
{
var employee_data = data.split(/\r/);
var table_data = '<table class="table table-bordered table-sm table-responsive table-striped table-hover ">';
for(var count = 0; count<employee_data.length; count++)
{
var cell_data = employee_data[count].split(",");
table_data += '<tr>';
for(var cell_count=0; cell_count<cell_data.length; cell_count++)
{
if(count === 0)
{
table_data += '<th>'+cell_data[cell_count]+'</th>';
}
else
{
table_data += '<td>'+cell_data[cell_count]+'</td>';
}
}
table_data += '</tr>';
}
table_data += '</table>';
$('#employee_table').html(table_data);
},
complete: function (data) {
$('#employee_table').DataTable();
alert("AJAX request successfully completed");
}
});
});
});
</script>
I want to display this layout in 5 rows at a time type using DataTable
so, please help me with this.
I tried many things but I'm unable to do it.
is there any way so I can achieve this?
You are trying to convert div as datatable.
Add one class in table tag, which will represent your table. Let's add myDataTable in table tag.
var table_data = '<table class="myDataTable table table-bordered table-sm table-responsive table-striped table-hover">';
now, convert the table to Datatable by replacing your code
$('#employee_table').DataTable(); // employee_table is actually an id of div
to
$('.myDataTable').DataTable(); // class that added in table tag

getJSON script returning "undefined"

I have had a look around on here and a number of other sites for the correct way to create an HTML table from and external json link and have come up with the below.
I am trying to pull the username and number of votes and display them in the table, multiple rows are created, all populated with "undefined".
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link re="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered table-striped table-hover" id="ragnarok_table">
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<script>
$(document).ready(function(){
$.getJSON("https://ark-servers.net/api/?object=servers&element=voters&key=[REMOVED]&month=current&format=json", function(data){
var ragnarok_data = '';
$.each(data, function(val){
ragnarok_data += '<tr>';
ragnarok_data += '<td>'+val.nickname+'</td>';
ragnarok_data += '<td>'+val.votes+'</td>';
ragnarok_data += '</tr>';
});
$('#ragnarok_table').append(ragnarok_data);
});
});
</script>
</body>
</html>
I can see that others have run into this issue too, however, this is my first time diving into Javascript; the other questions have completely different code and the answers dont seem to work here. Any help would be much appreciated, thanks.
Just use a .forEach on data.voters.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link re="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered table-striped table-hover" id="ragnarok_table">
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<script>
$(document).ready(function() {
$.getJSON("https://ark-servers.net/api/?object=servers&element=voters&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json", function(data) {
var ragnarok_data = '';
data.voters.forEach(function (val) {
ragnarok_data += '<tr>';
ragnarok_data += '<td>' + val.nickname + '</td>';
ragnarok_data += '<td>' + val.votes + '</td>';
ragnarok_data += '</tr>';
});
$('#ragnarok_table').append(ragnarok_data);
});
});
</script>
</body>
</html>
Or, if you are dead set on jQuery, modify your $.each to be on the array you want data from data.voters, and to properly get the value:
$.each(data.voters, function (ignore, val) {
The second argument is the value, the first argument is the index. See more here:
https://api.jquery.com/jQuery.each/
You can use .each as below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link re="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered table-striped table-hover" id="ragnarok_table">
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<script>
$(document).ready(function() {
$.getJSON("https://ark-servers.net/api/?object=servers&element=voters&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json", function(data) {
var ragnarok_data = '';
/*data.voters.forEach(function (val) {
*/
$(jQuery.parseJSON(JSON.stringify(data.voters))).each(function() {
ragnarok_data += '<tr>';
ragnarok_data += '<td>' + this.nickname + '</td>';
ragnarok_data += '<td>' + this.votes + '</td>';
ragnarok_data += '</tr>';
});
$('#ragnarok_table').append(ragnarok_data);
});
});
</script>
</body>
</html>

Error in getting values into my jquery

I have a problem in accessing server side value into my jQuery function. I gave my localhost path (NewsRecord.php) as the AJAX URL (it is working) but if I give server path it is not working... I don't know what is the problem -- the server URL prints the JSON data properly. Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<div data-role="page" data-theme="a">
<div data-role="header">
<h1>News Letter</h1>
</div>
<div data-role="content" id="level" ></div>
<div data-role="footer"></div>
<h4>Powered by Handigital</h4>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$.ajax({
url:'NewsRecord.php',
dataType:'json',
success:function(output) {
for(var u=0;u < output.length;u++)
{
$('#level').append('<div>Title :'+output[u].Title+'<br>Source :<a href='+output[u].links+'>'+output[u].Source+'</a><br>Category :'+output[u].Category+'</div><hr>');
}}
);
});
</script>
</body>
</html>
You need to place your for() loop in a function. This function can be given to the success property of the ajax method, where it will be called when the ajax call is complete (and is successful):
$(document).ready(function () {
$.ajax({
url: 'NewsRecord.php',
dataType: 'json',
success: function(output){
for (var u = 0; u < output.length; u++) {
$('#level').append('<div>Title :' + output[u].Title + '<br>Source :<a href=' + output[u].links + '>' + output[u].Source + '</a><br>Category :' + output[u].Category + '</div><hr>');
}
}
});
});

Categories

Resources