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

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>

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 to add button in javascript since the data that import in the html table is from JSON file

I am trying to add edit and delete button inside the column but the HTML table was created from JSON file and it is using for loop to print out the content. I don't know how to add extra button inside the column (green zone).
The button that plan to add will be replace in the 'undefined' col.
JSON code:
[
{
"userId":"ravjy",
"jobTitleName":"Developer",
"firstName":"Ran",
"lastName":"Vijay",
"preferredFullName":"Ran Vijay",
"employeeCode":"H9",
"region":"DL",
"phoneNumber":"34567689",
"emailAddress":"ranvijay.k.ran#gmail.com"
},
{
"userId":"mrvjy",
"jobTitleName":"Developer",
"firstName":"Murli",
"lastName":"Vijay",
"preferredFullName":"Murli Vijay",
"employeeCode":"A2","region":"MU",
"phoneNumber":"6543565",
"emailAddress":"murli#vijay.com"
}
]
<script>
fetch('employees.json')
.then(function (response) {
// The JSON data will arrive here
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
// If an error occured, you will catch it here
});
function appendData(data) {
//Extract Value for HTML HEADER.
var col=[];
for (var i = 0; i<data.length;i++){
for (var key in data[i]){
if (col.indexOf(key) === -1){
col.push(key);
}
}
}
//Add edit and delete header
col.push("Edit","Delete");
// 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 < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("myData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
[1]: https://i.stack.imgur.com/YpoDi.png
[2]: https://i.stack.imgur.com/pu7SB.png
Solution
Javascript map will help to get that working
const data = [
{
userId: "ravjy",
jobTitleName: "Developer",
firstName: "Ran",
lastName: "Vijay",
preferredFullName: "Ran Vijay",
employeeCode: "H9",
region: "DL",
phoneNumber: "34567689",
emailAddress: "ranvijay.k.ran#gmail.com",
},
{
userId: "mrvjy",
jobTitleName: "Developer",
firstName: "Murli",
lastName: "Vijay",
preferredFullName: "Murli Vijay",
employeeCode: "A2",
region: "MU",
phoneNumber: "6543565",
emailAddress: "murli#vijay.com",
},
];
function test(type, id) {
alert(type + " " + id);
}
function appendData(data) {
//Extract Value for HTML HEADER.
data = data.map((item) => {
item.Edit_Delete = `<Button type="button" onclick="test('Edit', '${item.userId}')">${item.userId}</Button>
<Button type="button" onclick="test('Delete', '${item.userId}')">${item.userId}</Button>`;
return item;
});
const col = [];
for (let i = 0; i < data.length; i++) {
for (let key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
//Add edit and delete header
// col.push("Edit","Delete");
// CREATE DYNAMIC TABLE.
const table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
let tr = table.insertRow(-1); // TABLE ROW.
for (let i = 0; i < col.length; i++) {
const th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (let i = 0; i < data.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
const tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
const divContainer = document.getElementById("myData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
appendData(data);
<!DOCTYPE html>
<html>
<body>
<div id ="myData"></div>
</body>
</html>

Create HTML Table Using JSON data in 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!

Filter Table Data, and Remove Filtered Column

I am currently using:
function searchNotes() {
const url = "http://localhost:2609/api/notes"
$.ajax({
url: url,
type: 'GET',
success: function (notesList) {
console.log(notesList)
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < notesList.length; i++) {
for (var key in notesList[i]) {
if (col.indexOf(key) === -1 && (key === 'title' || key === 'content' || key == 'category' || key == 'categoryId')) {
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 < notesList.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = notesList[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("listNotes");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
});
}
to create a html table using jquery. The table looks like this:
I want to filter the table by categoryId, as chosen in the dropdown at the top, then I want to remove the categoryId column. Any ideas how I could achieve this?
You need to use .sort() on the notesList object, something like this:
notesList.sort(function(a, b) {
return a.categoryId - b.categoryId;
});
Put it before appending the values to the html.
To 'remove' the categoryId column is very simple: Just remove the followingen bit from the if statement:
|| key == 'categoryId'
So your end result is something like this:
function searchNotes() {
const url = "http://localhost:2609/api/notes"
$.ajax({
url: url,
type: 'GET',
success: function (notesList) {
notesList.sort(function(a, b) {
return a.categoryId - b.categoryId;
});
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < notesList.length; i++) {
for (var key in notesList[i]) {
if (col.indexOf(key) === -1 && (key === 'title' || key === 'content' || key == 'category')) {
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 < notesList.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = notesList[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("listNotes");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
});
}

How to create a dynamic jquery data table with json data and ajax?

Im trying to create a dynamic data table with jquery and json. Im trying to exact the keys and set them as headers and then the values in the keys as rows in the table.
So far my code is:
<script type="text/javascript">
$('#action-button').click(function() {
$.ajax({
url: 'https://api.myjson.com/bins/1oaye',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'json',
success: function(data) {
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[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 < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[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);
},
type: 'GET'
});
});
</script>
but I keep getting an error that reads:
(index):80 Uncaught TypeError: Cannot set property 'innerHTML' of null
My JSON data structure
JSfiddle
How do I create a dynamic data table just based on the json data returned setting everything from the table headers to the values in the table?
I made two modifications in your code and it seems to be working after that.
1) Added a div with id 'showData' after div 'info'.
<div id="showData">
</div>
2) Enclosed $('#action-button').click(function() in $(document).ready(function().
$(document).ready(function() {
$('#action-button').click(function() {
$.ajax({
url: 'https://api.myjson.com/bins/1oaye',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'json',
success: function(data) {
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[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 < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[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);
},
type: 'GET'
});
});
});
The error says that it expecting a div with id 'showData'.
Firstly for data table you need to create the static header portion. I'm sharing my easiest code here.
<div class="table-responsive" style="margin-top:20px;">
<table id="tblPatientDiagnosed" class="table table-vcenter table-responsive table-condensed table-bordered display">
<thead>
<tr>
<th class="text-center" width="20%">Consultant Id</th>
<th class="text-center" width="30%">Consultant Name</th>
<th class="text-center" width="30%">Patinet Name</th>
<th class="text-center" width="20%">No. of time seen</th>
</tr>
</thead>
</table>
</div>
This is my static head of data-table.
Now in the document ready function you need to initialize it.
var tblPatientDiagnosed = '';
$(document).ready(function() {
tblPatientDiagnosed = $('#tblPatientDiagnosed').DataTable({
"bPaginate": true,
aaSorting:[],
"processing": true,
"sPaginationType": "full_numbers",
});
$("#action-button").on('click',function(){
tblPatientDiagnosed.fnClearTable();//fisrtly clearing data-table data if exist
$.ajax({
type: "POST",
cache: false,
url: "controllers/admin/add_treatment.php",
datatype:"json",
data: postData,
success: function(data) {
var parseData = JSON.parse(result);
var datalength = parseData.length;
for(var i=0; i < datalength; i++){
var staffId = parseData[i].consultant_id;
var staffLength = staffId.length;
for (var j=0;j<6-staffLength;j++) {
staffId = "0"+staffId;
}
staffId = staffPrefix+staffId;
tblPatientDiagnosed.fnAddData([staffId,'data1','data2','data3']);//write the varibale or data you got from ajax
}
}
});
});
fnadddata add row
<html>
<head>
<script>
function createdynamictable(yourdata)
{
//the parameter must be a json data
var parsedata = JSON.parse(yourdata)
var table = document.createElement("table");
for (var i = 0; i <= parsedata.length; i++)
{
tr = table.insertRow(-1);
for (var key in parsedata[0])
{
if (i == 0)
{
//Inserting columns fields to the table
var trCell = tr.insertCell(-1);
trCell.innerHTML = key;
}
else
{
//Inserting table values to the table
var trCell = tr.insertCell(-1);
trCell.innerHTML = parsedata[i-1][key];
}
};
}
var div = document.getElementById("showtable");
div.innerHTML = "";
div.appendChild(table);
}
</script>
</head>
<body>
<div id="showtable"></div>
</body>
</html>
How to generate a table with dynamic column titles and data from ajax JSON response.
//Javascript code
$.ajax({
"url": SitePath + "/Attendance/getEmployeeMonthYearlyReport",
"data": {
MonthYear: $("#txtEmpMonth").val()
},
"type": "GET",
"dataType": "JSON"
}).success(function (response) {
var objData1 = JSON.parse(response);
var myList = objData1.outdata.Table[0];
var tableHeaders = '';
var tableBody = '';
$.each(myList, function (k, v) {
tableHeaders += "<th>" + k + "</th>";
tableBody += "<td>" + v + "</td>";
});
$("#tblid").append('<thead><tr>' + tableHeaders + '</tr></thead>');
$("#tblid").append('<tbody><tr>' + tableBody + '</tr></tbody>');
})
#* Html code *#
<table class="table-striped table-bordered" id="tblid" align="center" width="100%"></table>

Categories

Resources