Create HTML Table Using JSON data in JavaScript - javascript

I am still suffering with JavaScript as I am newbie so please be patient to me and guide me step by step .. and please don't overload the comments with links because this made me lost
This is the try to bypass the CORS problem
<!DOCTYPE html>
<html>
<head>
<title>Read data from External JSON file using JavaScript</title>
<style>
* { font:17px 'Segoe UI'; }
table, th, td {
border: solid 1px #ddd;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<h3>
Data extracted from External JSON file and converted to an HTML table
</h3>
<div id='showTable'></div>
</body>
<script>
// Create XMLHttpRequest object.
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://www.encodedna.com/library/sample.json";
fetch(proxyurl + url)
.then(response => response.text())
.then(contents => createTableFromJSON(contents))
.catch(() => console.log("No Access " + url + " Response. Blocked By Browser?"))
//var oXHR = new XMLHttpRequest();
// Initiate request.
//oXHR.onreadystatechange = reportStatus;
//oXHR.open("GET", "https://www.encodedna.com/library/sample.json", true); // get json file.
//oXHR.send();
// Create an HTML table using the JSON data.
function createTableFromJSON(jsonData) {
var arrBirds = [];
arrBirds = JSON.parse(jsonData); // Convert JSON to array.
var col = [];
for (var i = 0; i < arrBirds.length; i++) {
for (var key in arrBirds[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// Create a dynamic table.
var table = document.createElement// Create table header.
var tr = table.insertRow(-1); // Table row.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // Table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
// Add JSON to the table rows.
for (var i = 0; i < arrBirds.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrBirds[i][col[j]];
}
}
// Finally, add the dynamic table to a container.
var divContainer = document.getElementById("showTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
};
</script>
</html>
I am getting No access ..
How can I read the JSON data and then convert to HTML table?

You got a couple of problems, but not with the CORS, you got the results from the request. The error came from the createTableFromJSON function.
The main problems:
Forgot to add ("table") after createElement
Two unnecessary loops
Wrong use of the JSON to get the Name
More tr than needed
Working code:
// Create XMLHttpRequest object.
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://www.encodedna.com/library/sample.json";
fetch(proxyurl + url)
.then(response => response.text())
.then(contents => createTableFromJSON(contents))
.catch((e) => console.log('error'))
// Create an HTML table using the JSON data.
function createTableFromJSON(jsonData) {
var arrBirds = [];
arrBirds = JSON.parse(jsonData); // Convert JSON to array.
var col = [];
for (var key in arrBirds) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
// Create a dynamic table.
var table = document.createElement("table") // Create table header.
var tr = table.insertRow(-1); // Table row. (last position)
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // Table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
tr = table.insertRow(-1); // add new row for the names
// Add JSON to the table rows.
for (var i = 0; i < arrBirds.length; i++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrBirds[i].Name;
}
// Finally, add the dynamic table to a container.
var divContainer = document.getElementById("showTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
};
* {
font: 17px 'Segoe UI';
}
table,
th,
td {
border: solid 1px #ddd;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight: bold;
}
<h3>
Data extracted from External JSON file and converted to an HTML table
</h3>
<div id='showTable'></div>
I hope this helps!

Related

API contains JSON data how to render on HTML and JavaScript?

I'm trying to have a bunch of memes show up on my HTML page. I'm using this URL https://api.memegen.link/images. I'm having lots of trouble trying to display images. I cannot figure out how to use this link. The link has what looks like a bunch of JSON code and the actual website has very little documentation on how to use it.
Here's the Javascript code. The HTML is just 2 divs and an input that has an onClick that call the function
$(document).ready(function imagesFromJSON() {
$.getJSON("https://api.memegen.link/images", function (data) {
var arrItems = []; // The array to store JSON items.
$.each(data, function (index, value) {
arrItems.push(value); // Push values in the array.
});
// Extract values for the table header.
var col = [];
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1); // Table row.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // Table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
// Add JSON data to the table as rows.
for (var i = 0; i < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
if (j === 2) { // The last JSON column has image urls.
// Create an <img> element to show the images.
var img = document.createElement('img');
img.src = arrItems[i].Image; // The image source from JSON array.
tabCell.appendChild(img);
}
else
tabCell.innerHTML = arrItems[i][col[j]];
}
}
// Finally, add the newly created <table> with data to a container.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
You can use fetch API in JavaScript directly to call the memeAPI.
For generating the table inside your JavaScript, you can use Template literals which will make it easy for you to construct the tables.
const getMemeBtn = document.querySelector("#get-meme");
getMemeBtn.addEventListener("click", getMeme);
function getMeme(){
fetch("https://api.memegen.link/images")
.then(res => res.json())
.then(data => {
let HTMLContent = `<table>
<tr>
<th>Meme Template</th>
<th>Meme Image</th>
</tr>
`;
for(let i = 0; i < 5; i++){
let memeImgURL = data[i].url;
let memeName = data[i].template;
HTMLContent += `
<tr>
<td>${memeName}</td>
<td><img width="100" height="100" src="${memeImgURL}"></td>
</tr>
`;
}
HTMLContent += `</table>`;
document.getElementById("memes").innerHTML = HTMLContent;
})
.catch(err => console.log(err));
}
<button type="button" id="get-meme">Get Meme</button>
<br><br><br><br>
<div id="memes"></div>

How can we implement Pagination using Javascript in simple HTML page

I'm trying to create an HTML table with pagination. I am calling a JSON data using a GET api and binding it as a dynamic table format. Pagination is handling in API by passing the page number. How can we simply handle the pagination in HTML Page with JS.
<!DOCTYPE html>
<html>
<head>
<title>Parent Child Mapping</title>
<style>
th,
td,
p,
input {
font: 14px Verdana;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
<div id="" class="pager-nav"></div>
</body>
<script>
function CreateTableFromJSON() {
var xhttp = new XMLHttpRequest();
var myBooks = [];
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
myBooks = JSON.parse(xhttp.responseText);
console.log("ok" + myBooks);
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[i]) {
console.log("myBooks..", myBooks[i])
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
};
xhttp.open("GET", "http://localhost:3000/", true);
xhttp.send();
}
</script>
</html>
This is the html code i have added for dynamic table.
You can create a row of buttons under your dynamic table, each of which correspond to the page number of results in your API.
Set an onclick event on the buttons to execute a GET request to your API with the correct parameters i.e. pageNumber, resultsPerPage -- this depends on how the API is set up.
Then you are effectively doing the same thing you are doing now, but with specific results based on page number and number of results/rows per page.
You can also cache the results to avoid further round trips on subsequent clicks of a previously clicked page number.

Change the Title of Elements on a Table

I'm currently using the following code to create a table based on a JSON API. I want to change the title of the table columns to be Name and Score instead of userName and userScore...
I have tried adjusting the forEach statement that creates the table columns, but that didn't work...
axios
.get("[ip censored]/scores")
.then(function(response) {
let sortedList = response.data.sort((a, b) => b.userScore - a.userScore);
console.warn(sortedList);
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < sortedList.length; i++) {
for (var key in sortedList[i]) {
if (
col.indexOf(key) === -1 &&
(key === "userName" || key === "userScore")
) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < sortedList.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = sortedList[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("leaderboard");
divContainer.innerHTML = "";
divContainer.appendChild(table);
})
.catch(function(error) {
console.error(error);
});
I also tried using CSS to make the tables look prettier, but it still didn't work.
Given you know the incoming key names and that they're consistent a simple inline if/else in your JavaScript should be all you need.
Try this:
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER
// This inline if says if col[i] is userName then set innerHTML to Name, else Score
th.innerHTML = col[i]==='userName' ? 'Name' : 'Score';
tr.appendChild(th);
}
Never mind, I figured it out. I used an if statement, and if col[i] equaled the value I wanted, I changed the value before I pushed the table.
You can use an if statement.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
var heading = "";
if(col[i] == "userName"){
th.innerHTML = "Name";
}
else if(col[i] == "userScore"){
th.innerHTML = "Score";
}
tr.appendChild(th);
}

Format each row in a dynamic table using javascript - HTML

im creating a dynamic table in a html form using the next function:
<script>
function poblarTabla() {
// CREATE DYNAMIC TABLE.
var table = document.createElement('table');
// SET THE TABLE ID.
// WE WOULD NEED THE ID TO TRAVERSE AND EXTRACT DATA FROM THE TABLE.
table.setAttribute('id', 'tablaDeCuentas');
var arrHead = new Array();
arrHead = ['Emp. ID', 'Emp.Name', 'Designation'];
var arrValue = new Array();
arrValue.push(['1', 'Green Field', 'Accountant']);
arrValue.push(['2', 'Arun Banik', 'Project Manager']);
arrValue.push(['3', 'Dewane Paul', 'Programmer']);
var tr = table.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th'); // TABLE HEADER.
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
for (var c = 0; c <= arrValue.length - 1; c++) {
tr = table.insertRow(-1);
for (var j = 0; j < arrHead.length; j++) {
var td = document.createElement('td'); // TABLE DEFINITION.
td = tr.insertCell(-1);
td.innerHTML = arrValue[c][j]; // ADD VALUES TO EACH CELL.
}
}
document.body.appendChild(table);
}
</script>
This works correctly, what i want to do now is format each row using this format:
<tr align="left" valign="middle"><td bgcolor="#005C84" width="240" height="30"> <p style="color: white; font-size: 14px;font-family: Arial,sans-serif;font-weight: normal;text-decoration: none; display:block; padding:0; margin:0; margin-left:10px">ID de cuenta:</p></td><td bgcolor="#e5f0c3"><p style="color: #666; font-size: 14px;font-family: Arial,sans-serif;font-weight: normal;text-decoration: none; display:block; padding:0; margin:0; margin-left:10px"></p></td></tr>
So each time that a row is created, is displayed in the form with this format. Can anyome give me a hand? Thnks in advance!
Instead of using inline styles, you can try creating classes and then add them as you like while you are creating the table or its rows.
style.css
.table-style{
align: left;
valign: middle;
}
then in your javascript:
table.classList.add('table-style');

test.html:208 Uncaught ReferenceError: createtable is not defined

Ive been trying to make a webpage that can read an excel file and then create a table out of it. I already got the table generating part to work, but I can't get the loading part to work. I am getting an error that says that my function is not defined.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table Example</title>
</script> -->
</head>
<body>
<script type="text/javascript" src="http://cdn.jsdelivr.net/alasql/0.3/alasql.min.js">
var myBooks
function createtable(){
(function () {
'use strict';
}
}
}
alasql('SELECT * FROM XLSX("test.xlsv")').then(function(data){
myBooks = console.log(data);
});
angular
.module('jfy')
.factory('ImportExportToExcel', ImportExportToExcel);
function ImportExportToExcel(alasql, $log, $rootScope) {
return {
importFromExcel: function (event) {
if (event.target.files.length == 0) {
return false;
}
alasql('SELECT * FROM FILE("test.xlsv",{headers:true})', [event], function (data) {
$rootScope.$broadcast('import-excel-data', data);
});
},
exportToExcel: function (fileName, targetData) {
if (!angular.isArray(targetData)) {
$log.error('Can not export error type data to excel.');
return;
}
alasql('SELECT * INTO XLSX("' + fileName + '.xlsx",{headers:true}) FROM ?', [myBooks]);
}
}
}
})();
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
object.onclick = function(){table};
}
</script>
<input type="button" onclick="createtable()" value="Create Table From JSON" />
<div id="showData"></div>
</body>
</html>

Categories

Resources