JSON to HTML Table JavaScript Not Working
I've written this function to display the contents of the JSON file in an HTML table. However, it's returning as undefined.
I don't seem to be able to work out why this is happening. The console log displays the data just fine, but not the HTML table.
I'm wondering if it has something to do with the way arrays are parsed?
I want to keep the code short and clean, but wondering if there is a better way to do this without the undefined error. Maybe Vanilla JavaScript is better, using fetch?
Live page is found here: LBRYnomics
Thanks in advance!
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub)
var sub_data = '';
$.each(data, function(key, value) {
sub_data += '<tr>';
sub_data += '<td>' + value.ranks + '</td>';
sub_data += '<td>' + value.vanity_names + '</td>';
sub_data += '<td>' + value.claim_ids + '</td>';
sub_data += '<td>' + value.subscribers + '</td>';
sub_data += '</tr>';
console.log(key + '=' + value);
});
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>
You have multiple different arrays for each of those properties.
Assuming they are all in same relationship order you can loop over one of the arrays and use the iteration index to access corresponding elements from each of the other arrays.
Something like:
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub);
var sub_data = '';
$.each(data.ranks, function(i, rank) {
sub_data += '<tr>';
sub_data += '<td>' + rank + '</td>';
sub_data += '<td>' + data.vanity_names[i] + '</td>';
sub_data += '<td>' + data.claim_ids[i] + '</td>';
sub_data += '<td>' + data.subscribers[i] + '</td>';
sub_data += '</tr>';
//console.log(key + '=' + value);
});
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>
I think after inspecting the api it looks the items are put in different array with no connection but they have the same length. So assuming that attrbute1 at index N maps to attribute2 at index N and so on.
jQuery(document).ready(function($) { $.getJSON('https://www.brendonbrewer.com/lbrynomics/subscriber_counts.json', function(data) {
var humanTimeSub = `${data.human_time_utc}`
$(".human-time-sub").html(humanTimeSub)
var sub_data = '';
for(var i=0; i<data.ranks.length; i++){
//$.each(data.ranks, function(key, value) {
sub_data += '<tr>';
sub_data += '<td>' + data.ranks[i] + '</td>';
sub_data += '<td>' + data.vanity_names[i] + '</td>';
sub_data += '<td>' + data.claim_ids[i] + '</td>';
sub_data += '<td>' + data.subscribers[i] + '</td>';
sub_data += '</tr>';
//console.log(key + '=' + value);
//});
}
$('#sub-stats').append(sub_data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="sub-stats">
<tr>
<th>RANK</th>
<th>VANITY NAME</th>
<th>CLAIM ID</th>
<th>SUBS</th>
</tr>
</table>
Related
I have created a jQuery/ajax API call function to read the JSON data and insert it into the HTML table and it works fine, But I want to auto-reload the table data after 5Sec when a button is clicked.
I tried some codes to make it work. How can I fix it?
$(document).ready(function() {
$.getJSON("http://mydevtest.in/wp-json/pmprocurrencies/v1/all", function(data){
var currency_Data = '';
$.each(data, function(key, value){
currency_Data += '<tr>';
currency_Data += '<td>' + value.id + '</td>';
currency_Data += '<td>' + value.country_alpha + '</td>';
currency_Data += '<td>' + value.currency_code + '</td>';
currency_Data += '<td>' + value.currency_sign + '</td>';
currency_Data += '<td>' + value.currency_rate + '</td>';
currency_Data += '<td><button type="submit" id="delBtn" value="' + value.id + '">x</button></td>';
currency_Data += '</tr>';
});
$("#currency_tables").append(currency_Data);
// Reload the table data on "#addcr" button click.
$("#addcr").on("click", function(){
$("#currency_tables").load(location.href + " #currency_tables");
});
});
});
You can use setTimeout(function,milliseconds) for this.
https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
So, I was able to find the solution myself, below is the working code, But I think it's not the professional solution to repeat the same function to achieve the result. If anyone has any better idea, Please suggest.
$(document).ready(function() {
$.getJSON("http://mydevtest.in/wp-json/pmprocurrencies/v1/all", function(data){
var currency_Data = '';
$.each(data, function(key, value){
currency_Data += '<tr>';
currency_Data += '<td>' + value.id + '</td>';
currency_Data += '<td>' + value.country_alpha + '</td>';
currency_Data += '<td>' + value.currency_code + '</td>';
currency_Data += '<td>' + value.currency_sign + '</td>';
currency_Data += '<td>' + value.currency_rate + '</td>';
currency_Data += '<td><button type="submit" id="delBtn" value="' + value.id + '">x</button></td>';
currency_Data += '</tr>';
});
$("#currency_tables").html(currency_Data);
// Reload the table data on "#addcr" button click.
});
$("#addcr").on("click", function(){
setTimeout(function(){
$.getJSON("http://mydevtest.in/wp-json/pmprocurrencies/v1/all", function(data){
var currency_Data = '';
$.each(data, function(key, value){
currency_Data += '<tr>';
currency_Data += '<td>' + value.id + '</td>';
currency_Data += '<td>' + value.country_alpha + '</td>';
currency_Data += '<td>' + value.currency_code + '</td>';
currency_Data += '<td>' + value.currency_sign + '</td>';
currency_Data += '<td>' + value.currency_rate + '</td>';
currency_Data += '<td><button type="submit" id="delBtn" value="' + value.id + '">x</button></td>';
currency_Data += '</tr>';
});
$("#currency_tables").replaceWith(currency_Data);
// Reload the table data on "#addcr" button click.
});
}, 4000)
});
});
Pasting the GET api url on a browser shows me the json data. It looks like this:
{"Count":2,"Items":[{"date":{"S":""},"time":{"S":""},"email":{"S":"test1#email.com"},"name":{"S":""},"phone":{"S":""},"desc":{"S":""}},{"date":{"S":"3/7/21"},"time":{"S":"8:00am - 9:00am"},"email":{"S":"binia#gmu.edu"},"name":{"S":"Bini A"},"phone":{"S":"1234567890"},"desc":{"S":"I like your cut G"}}],"ScannedCount":2}
But When I try to use ajax request to loop through the data, it returns [Object Object]. Please help me figureout this error.
Here is my frontend code:
$.ajax({
url: 'my URL goes here ...',
type: "GET",
success: function (data) {
alert('data fetched!');
var tr = '<tr><th>Full Name</th><th>Phone Number</th><th>Email</th><th>Requested Date</th><th>Requested Time</th><th>Customer Feedback</th></tr>'; // row
// loop through data and display on table
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name + '</td>';
tr += '<td>' + Item.phone + '</td>';
tr += '<td>' + Item.email + '</td>';
tr += '<td>' + Item.date + '</td>';
tr += '<td>' + Item.time + '</td>';
tr += '<td>' + Item.desc + '</td></tr>';
});
$('#createdHoursDb').append(tr); // update table
console.log(tr);
},
error: function () {
alert('fetch request failed!');
}
});
Here is the response on the page:
[Object Object] on each cell of each row.
As you can see, the value of each property is also an object: "name":{"S":""}
So you can write:
...
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name.S + '</td>';
tr += '<td>' + Item.phone.S + '</td>';
tr += '<td>' + Item.email.S + '</td>';
tr += '<td>' + Item.date.S + '</td>';
tr += '<td>' + Item.time.S + '</td>';
tr += '<td>' + Item.desc.S + '</td></tr>';
});
...
You are seeing object because you have an object inside it {"S": ""}. Either you need to convert your data in the required form or you need to use like Item.name.S everywhere.
const data = {"Count":2,"Items":[{"date":{"S":""},"time":{"S":""},"email":{"S":"test1#email.com"},"name":{"S":""},"phone":{"S":""},"desc":{"S":""}},{"date":{"S":"3/7/21"},"time":{"S":"8:00am - 9:00am"},"email":{"S":"binia#gmu.edu"},"name":{"S":"Bini A"},"phone":{"S":"1234567890"},"desc":{"S":"I like your cut G"}}],"ScannedCount":2};
let tr = '<tr><th>Full Name</th><th>Phone Number</th><th>Email</th><th>Requested Date</th><th>Requested Time</th><th>Customer Feedback</th></tr>'; // row
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name.S + '</td>';
tr += '<td>' + Item.phone.S + '</td>';
tr += '<td>' + Item.email.S + '</td>';
tr += '<td>' + Item.date.S + '</td>';
tr += '<td>' + Item.time.S + '</td>';
tr += '<td>' + Item.desc.S + '</td></tr>';
});
$('#createdHoursDb').append(tr); // update table
console.log(tr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="createdHoursDb">
</table>
I am trying to append some data to a Datatables tbody. I do recieve the data when I console.log() the data, but the data does not show when I try to append it to my Datatable (The id of my table is 'example' btw). I do not know where to go in terms of debugging this as well.
asyncRequest.then((tracks) => {
var tableData = '';
// rows
for (track in tracks) {
tableData += '<tr>';
tableData += '<td>' + tracks[track]._id + '</td>';
tableData += '<td>' + tracks[track].Position + '</td>';
tableData += '<td>' + tracks[track].Track + '</td>';
tableData += '<td>' + tracks[track].Artist + '</td>';
tableData += '<td>' + tracks[track].Streams + '</td>';
tableData += '<td>' + tracks[track].Url + '</td>';
tableData += '<td>' + tracks[track].Date + '</td>';
tableData += '</tr>';
}
console.log(tableData);
$(document).ready(function () {
var table = $('#example').DataTable();
$(table).find('tbody').append(tableData);
});
});
</script>
tracks: [0 … 99]
0:
_id: "5e8d677a6e5216bc865e084a"
Position: 1
Track: "Dance Monkey"
Artist: "Tones And I"
Streams: 6155025
Url: "https://open.spotify.com/track/1rgnBhdG2JDFTbYkYRZAku"
Date: "1/1/20"
Can u try this one fisrt destroy then append then refresh it
and put your document ready out of request and initialize there
$(document).ready(function () {
var table = $('#example').DataTable();
});
then after u take data appen it destroy it and refresh it
asyncRequest.then((tracks) => {
var tableData = '';
// rows
for (track in tracks) {
tableData += '<tr>';
tableData += '<td>' + tracks[track]._id + '</td>';
tableData += '<td>' + tracks[track].Position + '</td>';
tableData += '<td>' + tracks[track].Track + '</td>';
tableData += '<td>' + tracks[track].Artist + '</td>';
tableData += '<td>' + tracks[track].Streams + '</td>';
tableData += '<td>' + tracks[track].Url + '</td>';
tableData += '<td>' + tracks[track].Date + '</td>';
tableData += '</tr>';
}
console.log(tableData);
$('#example').DataTable().destroy();
$('#example').find('tbody').append(str);
$('#example').DataTable().draw();
});
I am tying to fetch the data from firebase just like make single row of first element of all the headings in firebase database. i.e first element of Amount, key, time, total, Number should make a single row and then so on.
I am trying with foreach loop but I can refer to the correct refrence of firebase
//html code
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Amount</th>
<th>Key</th>
<th>Number</th>
<th>Time</th>
<th>Total</th>
</table>
//Javascript code
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.Amount + '</td>';
content += '<td>' + val.Key + '</td>';
content += '<td>' + val.Number + '</td>';
content += '<td>' + val.Time + '</td>';
content += '<td>' + val.Total + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
I am getting undefined instead of values
I seem to only be able to find the answer to this problem in JQuery and I would really like a pure JS solution.
I have a dynamically generated table that I build from a parsed JSON file. I added a checkbox for each row. My question is, do I also have to generate a unique ID or Class for each cell? How can I return a variable containing the data from just the row selected?
var watchLog = new XMLHttpRequest();
var rowChecked;
watchLog.onreadystatechange = function () {
if(watchLog.readyState === 4) {
var status = JSON.parse(watchLog.responseText);
var watchLogCell = '';
for (var i = 0; i < status.length; i += 1) {
watchLogCell += '<tr>';
watchLogCell += '<th scope="row" class="rowHeader"><input type="checkbox" name="selectRow' + i + '"
onclick="function rowData(){if(this.checked){rowChecked = ' + status[i]["Load ID"] + '; return console.log(rowChecked);};">';
watchLogCell += '<td>' + status[i]["Load ID"] + '</td>';
watchLogCell += '<td>' + status[i]["Carrier Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Vendor Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Load Status"] + '</td>';
watchLogCell += '<td>' + status[i]["Truck Status"] + '</td>';
watchLogCell += '<td>' + status[i]["DA First"] + '</td>';
watchLogCell += '<td>' + status[i]["PO Number"] + '</td>';
watchLogCell += '<td>' + status[i]["Buyer No"] + '</td>';
watchLogCell += '<td>' + status[i]["Comments"] + '</td>'
watchLogCell += '</tr>';
}
document.getElementById('tableBody').innerHTML = watchLogCell;
}
};
watchLog.open('GET', 'watchlogic.json');
watchLog.send();
You can try something like
//use this to store the mapping of values, assuming loadid is unique for each record else a unique property of the record has to be used
var watchlogic = {};
var watchLog = new XMLHttpRequest();
watchLog.onreadystatechange = function () {
if (watchLog.readyState === 4) {
var status = JSON.parse(watchLog.responseText);
var watchLogCell = '';
for (var i = 0; i < status.length; i += 1) {
//store the record in watchlogic with key as the unique value
watchlogic[status[i]["Load ID"]] = status[i];
watchLogCell += '<tr>';
watchLogCell += '<th scope="row" class="rowHeader"><input type="checkbox" name="selectRow' + i + '" onclick="onSelect(this)" data-loadid="' + status[i]["Load ID"] + '">'; //store the current record's unique value in an attribute
watchLogCell += '<td>' + status[i]["Load ID"] + '</td>';
watchLogCell += '<td>' + status[i]["Carrier Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Vendor Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Load Status"] + '</td>';
watchLogCell += '<td>' + status[i]["Truck Status"] + '</td>';
watchLogCell += '<td>' + status[i]["DA First"] + '</td>';
watchLogCell += '<td>' + status[i]["PO Number"] + '</td>';
watchLogCell += '<td>' + status[i]["Buyer No"] + '</td>';
watchLogCell += '<td>' + status[i]["Comments"] + '</td>'
watchLogCell += '</tr>';
}
document.getElementById('tableBody').innerHTML = watchLogCell;
}
};
watchLog.open('GET', 'watchlogic.json');
watchLog.send();
function onSelect(el) {
//here el is the clicked element then use the data attribute value to get the unique valeu of the record and use that to get the record form the watchlogic object
var status = watchlogic[el.dataset.loadid]; //or this.getAttribute('data-loadid') for <= IE10
console.log(status)
}