I need help on how to create table from data fetch from API server in html.
A possible duplicate of this question
I need to request json data from a url, then use that data to dynamically create table in html.
Below are my test.html
<!DOCTYPE html>
<html>
<head>
...
...
</head>
<body>
...
...
...
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Activity</h3>
</div>
<div id = "showData" class="box-body"></div>
</div>
</div>
</div>
<script src="../static/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="../static/plugins/jQueryUI/jquery-ui.min.js"></script>
<script>
$.ajax({
url: "http://127.0.0.1:4220/pipeline/v1/bpwi/",
success: function (data) {
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
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 = myBooks[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
})
</script>
</body>
</html>
Expected ajax response is something like this
[
{
"ID": "1",
"Name": "Computer",
"Category": "Computers",
"Price": "125.60"
},
{
"ID": "2",
"Name": "Blue",
"Category": "Sport",
"Price": "56.00"
},
{
"ID": "3",
"Book Name": "Science",
"Category": "Science",
"Price": "210.40"
}
]
I have refreshed my browser many times but the result is not good.
Here is the result
-----------------------------------------------------------------
Activity
-----------------------------------------------------------------
0
[
{
"
I
D
"
:
"
1
"
...
...
I am really new to javascript and some of good example I found is the possible question I posted above and here but both did not show a clear example on how to implement http request for getting the data from external source.
I really hope someone can pointed out for me what I did wrong in this code.
Thank you for your help and suggestion.
Related
I am trying to achieve something like this.
I am getting a json response after hitting a particular api command (a curl command let's say). I need to convert this result to an html. For this I am thinking of storing the result in an environment variable.
My intentions is to read this variable and so read the json data.
How can I read a environment variable in js?
I am using below program to map the json to html table.
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table</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>
</body>
<script>
function CreateTableFromJSON() {
var myBooks = [
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
// 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);
}
</script>
</html>
As Quentin says: you can't, but look into Local Storage instead.
JavaScript, running client-side in an HTML document, has no access to environment variables at all. So you can't.
I've already built a table with DOM methods, taking in input the number of row and column. Now I need to take the number of row and column by the element of the array myBooks and put in my table the values of the same array. How should I do?
<!DOCTYPE html>
<html>
<head>
<title>tabella dom</title>
<script type="text/javascript" src="tabellaDom.js"></script>
</head>
<body>
<form name="numeri">
Inserisci due valori: <br>
<input name="valore1">
<input name="valore2">
<br>
<input type="button" name="creaTabella" value="Crea Tabella" onclick="creaTable(numeri.valore1.value, numeri.valore2.value);">
<br>
<div id="myDynamicTable"></div>
</form>
</body>
</html>
function creaTable(a, b) {
var tableDiv = document.getElementById("myDynamicTable");
var tbl = document.createElement('table');
tbl.setAttribute("id", "tabella");
var tbdy = document.createElement('tbody');
tbl.appendChild(tbdy);
tbl.border = '1';
for (var j = 0; j < a; j++) {
const tr = document.createElement('tr');
console.log('tr.value');
tbdy.appendChild(tr);
const btnDelete = document.createElement('input');
btnDelete.setAttribute("type", "button");
btnDelete.setAttribute("value", "-");
tr.appendChild(btnDelete);
btnDelete.onclick = function() {
tr.remove();
};
for (var k = 0; k < b; k++) {
var td = document.createElement('td');
td.width = '75';
td.appendChild(document.createTextNode("Cella " + j + "," + k));
tr.appendChild(td);
}
}
tableDiv.appendChild(tbl);
}
var myBooks = [{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
var data="";
b--;
if(b==0){
data=myBooks[a-1]['Book ID'];
}
else if(b==1){
data=myBooks[a-1]['Book Name'];
}
else if(b==2){
data=myBooks[a-1]['Category'];
}
else if(b==3){
data=myBooks[a-1]['Price'];
}
Try this code. Here a is number of row and b is number of column
G'day,
So i've got this code to display a JSON file in a table and it works. What I want to know is how can I add a search bar for the table (I want to search by postcode)
function CreateTableFromJSON() {
var Data = [
{
"Service name": "3Bridges Community Incorporated",
"Physical Address Line 1": "1/72 Carwar Avenue",
"Physical Address Suburb": "CARSS PARK",
"Physical Address State": "NSW",
"Physical Address Post Code": 2221,
"Care Type": "Home Care Places",
"Residential Places": null,
"Home Care Low Places": 35,
"Home Care High Places": 10,
"Transition Care Places": null
}
]
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
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");
table.className += "alt";
// 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);
}
Some help would be greatly appreciated!
And here is my HTML:
<div class="table-wrapper">
<div id="showData"></div>
</div>
I'd say do a onchange event to a text input, and every time user defocus the text box, it will call your createTable function with a zip in parameter.
function search(zip)
{
CreateTableFromJSON(zip);
}
function CreateTableFromJSON(zip) {
var Data = [
{
"Service name": "3Bridges Community Incorporated",
"Physical Address Line 1": "1/72 Carwar Avenue",
"Physical Address Suburb": "CARSS PARK",
"Physical Address State": "NSW",
"Physical Address Post Code": 2221,
"Care Type": "Home Care Places",
"Residential Places": null,
"Home Care Low Places": 35,
"Home Care High Places": 10,
"Transition Care Places": null
}
]
//apply filter
Data=Data.filter(d=>d["Physical Address Post Code"]==zip || !zip)
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
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");
table.className += "alt";
// 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);
}
HTML .
<div class="table-wrapper">
<input type="text" name="searchText" value="" onchange="search(this.value)">
<div id="showData"></div>
</div>
I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.
JSON file
[
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
HTML and JS
<script>
$(document).ready(function () {
$.getJSON("result.json", function (data) {
var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
$.each(data, function (index, value) {
arrItems.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
});
// EXTRACT VALUE FOR 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);
}
}
}
// 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 < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[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);
});
});
Hi gusy, I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Is there any jQuery or javascript library that generates a dynamic table given json data?
I don't want to define the columns, the library should read the keys in the json hash and generate columns.
Of course, I can myself iterate through the json data and generate the html table. I just want to know if any such library exists which I can simply reuse.
Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.
Code snippet:
var myList = [
{ "name": "abc", "age": 50 },
{ "age": "25", "hobby": "swimming" },
{ "name": "xyz", "hobby": "programming" }
];
// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>
I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.
Demo
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i = 0, maxi = arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j = 0, maxj = columns.length; j < maxj; ++j) {
var td = _td_.cloneNode(false);
var cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table) {
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i = 0, l = arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
columnSet.push(key);
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
document.body.appendChild(buildHtmlTable([{
"name": "abc",
"age": 50
},
{
"age": "25",
"hobby": "swimming"
},
{
"name": "xyz",
"hobby": "programming"
}
]));
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"email1#domain.com"},{"name": "name2","link":"email2#domain.com"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.
Example:
var transform = {"tag":"table", "children":[
{"tag":"tbody","children":[
{"tag":"tr","children":[
{"tag":"td","html":"${name}"},
{"tag":"td","html":"${age}"}
]}
]}
]};
var data = [
{'name':'Bob','age':40},
{'name':'Frank','age':15},
{'name':'Bill','age':65},
{'name':'Robert','age':24}
];
$('#target_div').html(json2html.transform(data,transform));