Dynamic column header in datatable from json array - javascript

I want to populate a Datatable with a dynamic column header and column data. I can populate dynamic column data successfully, but I can't achieve a dynamic column. I am using an array I get from a JSON AJAX request. My code is this:
<body>
<table id="example" class="display" cellspacing="0" width="100%" border="1"></table>
</body>
var JSONResult = '{"column1":"data1","column2":"data2","column3":"data3","columnN":"dataN"}';
var row_dtable = new Array();
var dtable_api = $('#example').dataTable();
$.each(JSONResult , function(key, value) {
row_dtable.push(value);
});
dtable_api.api().row.add(row_dtable).draw(false);
Thanks in advance.

Datatables doesn't have the ability to change it's structure once being created. You have to destroy it and then re-create with a new set of columns.
Additional reading: How to dynamically change Datatables multiple column headers using ajax and jquery without refreshing the webpage?

Ideally your JSONResult will always have the same columns and only data will be updated. For this the solution will be to create the columns once in the header of your table and then using the datatable API to add the data.
First you should change your table HTML like this, which shouldn't be a problem.
<body>
<table id="example" class="display" cellspacing="0" width="100%" border="1">
<thead>
<tr></tr>
</thead>
</table>
</body>
Then you create the headers through jQuery
var JSONResult = [{ "column1": "data1", "column2": "data2", "column3": "data3", "columnN": "dataN" },
{ "column1": "data1", "column2": "data2", "column3": "data3", "columnN": "dataN" }];
$.each(JSONResult[0], function (key, value) {
$('#example thead tr:first-child').append($('<th>', {
text: key
}));
});
And last, add the data to dataTable
var row_dtable = new Array();
var dtable_api = $('#example').dataTable();
$.each(JSONResult, function (i, l) {
$.each(l, function (key, value) {
console.log(key + " " + value);
row_dtable.push(value);
});
dtable_api.api().row.add(row_dtable).draw(false);
});

Related

Displaying array data from session to html table

I've copied data of a html table on page 1 in an array obj(arrData). And i've save that arrData into the session storage. Now on page 2, how do i display the data from the arrData to the html table. New in JS. Thanks in advance
PAGE 1 JS
var arrData=[];
$("#checkout").on('click',function(){
$("#table tr").each(function(){
var currentRow=$(this);
var col1_value=currentRow.find("td:eq(0)").text();
var col2_value=currentRow.find("td:eq(1)").text();
var obj={};
obj.col1=col1_value;
obj.col2=col2_value;
arrData.push(obj);
sessionStorage.myArrData=JSON.stringify(arrData);
});
console.log(arrData);
});
PAGE 2
<table class="table table-checkout" id="table">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
PAGE 2 JS
var arrData = JSON.parse(sessionStorage.myArrData);
You need to use sessionStorage.setItem("foo", 12) rather than sessionStorage.foo = 12;
The latter is attaching a new property to the javascript object, not talking to the browser session API. When the page reloads, the object you attached is gone.
To get the item back, use sessionStorage.getItem
Mozilla docs for sessionStorage including setItem and getItem
Once you've done that, you will need a way of creating new table rows in the table. There are a multitude of frameworks for this purpose, but you can also build tables (with a few more steps than with other elements) yourself
How to insert row in HTML table body in Javascript?
As I understand from above, You have data in array of objects after var arrData = JSON.parse(sessionStorage.myArrData);, in below format..
arrData:
[
{col1:"Item1", col2:"quantity1"},
{col1:"Item1", col2:"quantity1"},
...
]
Now to display this data on Page 2
var rows = "";
arrData.map((row)=>{
var row = '<tr><td>'+row.col1+'</td><td>'+row.col2+'</td></tr>';
rows = rows+row;
})
var tbody = document.queryselector('#table tbody');
tbody.innerHTML = rows;

How to activate sorting in this table?

I am using DataTable plugin. The examples in the linked page are great. But I have a problem.
In the example user may sort the datatable after doing a search. I successfully do this. But when I created a filter, the sorting is messed up.
This is the expected sequence:
Page shows all data in the datatable
User do a filter (Show data by some filter. Like by date, by status, by country etc)
Page show certain data with the searched filter
User may do a search using text to view less data
User may do sort by column
In my script, the code works until point 3. When user do a search the filtered data is reset to show all data(not-filtered)
How do I deal with this?
This is my table:
<table id="tbl_surat_all" class="table table-striped table-bordered table-hover dataTables-example" >
<thead>
<tr>
<th class='text-center' width="1%">No</th>
<th class="text-center" width="10%">ID Proyek</th>
</tr>
<tbody><!--Data collected from php--></tbody>
</thead>
<tbody>
The jQuery:
$('.dataTables-example').DataTable({
pageLength : 25,
responsive : true,
dom : '<"html5buttons"B>lTfgitp',
buttons : [
{extend: 'copy'},
{extend: 'csv', title : "list<?php echo date('d/m/Y'); ?>"},
{extend: 'excel', title : "list<?php echo date('d/m/Y'); ?>"},
{extend: 'pdf', title : "list<?php echo date('d/m/Y'); ?>"},
{extend: 'print',
customize: function (win){
$(win.document.body).addClass('white-bg');
$(win.document.body).css('font-size', '10px');
$(win.document.body).find('table').addClass('compact').css('font-size', 'inherit');
}
}
]
});
This this the filter do (It's ajax success call):
var row;
var no = 1;
$('#tbl_surat_all tbody tr').remove();
$.each(response, function(index, data) {
row = "<tr><td>"+ no++ +"</td><td>"+data.idproyek+"</td></tr>";
$('#tbl_surat_all tbody').append(row);
});
Note:
the conclusion is how do I copy the search behavior (default from the library) to my filter (my own created jquery) behavior?
If you look at the search api, you can either search on the table as shown.
var table = $('#example').DataTable();
// #myInput is a <input type="text"> element
$('#myInput').on( 'keyup', function () {
table.search( this.value ).draw();
} );
Or you can name your columns when you initialize the datatable and search each column for text and apply that to the datatable.
columns: [
{
name: 'colName',
data: 'colData',
type: 'date'
}
searching on the column would be
var col = table.columns('colname:name');
col.search('searchTerm');
table.draw();

populating table with jquery and json

I would like to populate an existing table with json data. I found an example on stackoverflow which does this but with only one column of data. The json data has three sets of data which requires obviously 3 columns. I have experimented with only one row but the jquery code (below) incorrectly displays the table.
<table class="table">
<tr id="row1">
<td = "col1"></td>
<td = "col2"></td>
<td = "col3"></td>
function myFunction() {
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];
$.each(data, function(key, value) {
$("#row1").eq(key).find('td').text(value.indx);
$("#row1").eq(key).find('td').text(value.amt);
$("#row1").eq(key).find('td').text(value.jDate);
});
}
OUTPUT IN BROWSER: 167 167 167
It is displaying the last field in all three columns. Any advise on how to do get table to display the correct values would be appreciated.
Your code is updating ALL CELLS with value.indx, then with value.amt and finally with value.jDate... So fast that you only see the final result.
I think what you want to achieve is something more like in this CodePen :
function myFunction() {
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];
$.each(data, function(key, value) {
$("table").find('tr').eq(key).find("td").eq(0).text(value.indx);
$("table").find('tr').eq(key).find("td").eq(1).text(value.amt);
$("table").find('tr').eq(key).find("td").eq(2).text(value.jDate);
});
}
myFunction();
Obviously you have to add rows dynamically into your table, because your data array may contain different amount of objects.
Try this code.
Here we have table which is populated with new rows for each element of data array.
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3344.4,"vendor":22,"jDate":168},
{"indx":3,"amt":1414.1,"vendor":21,"jDate":169},
{"indx":4,"amt":3441.3,"vendor":31,"jDate":1610}];
$.each(data, function(key, value) {
var tr = $("<tr>");
tr.append($("<td>").text(value.indx));
tr.append($("<td>").text(value.amt));
tr.append($("<td>").text(value.vendor));
tr.append($("<td>").text(value.jDate));
$("#table").append(tr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" border="1">
</table>

Populate Existing Table With Data Using JQuery

Using the method below I am trying to populate an existing table with data however the function fills it with the same values. I can perform such action adding append method, but in my case the table should be exist already :)
HTML
<table class="table">
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
</table>
JQuery
$.each(data, function(i, value){
$(".table td").text(value.product);
});
var data= [
{"product":"RD0"},
{"product":"RD1-184"},
{"product":"RD1-185"}
]
Here's a code snipped using your sample from above with a demo in JSFiddle.
$(function() {
var data = [{
"product": "RD0"
}, {
"product": "RD1-184"
}, {
"product": "RD1-185"
}];
var table = $('.table');
$.each(data, function(i, value) {
table.find('tr').eq(i).find('td').text(value.product);
});
});
https://jsfiddle.net/qur62os2/
you probably need something like this:
$(".table").find('td').each(function(i) {
$(this).text(data[i].product);
});
https://jsfiddle.net/ahmadabdul3/fn8q8e3x/

JSON to html STYLED table

We can convert a set of JSON data to html table by below code:
$.each(data, function(key, val) {
var tr=$('<tr></tr>');
$.each(val, function(k, v){
$('<td>'+v+'</td>').appendTo(tr);
});
tr.appendTo('#display');
});
The html table is:
<table border='1' id="display">
<thead>
<tr>
<th>firstcol</th>
<th>loc</th>
<th>lastA</th>
<th>mTime</th>
<th>nTime</th>
<th>Age</th>
<th>ction</th>
</tr>
</thead>
</table>
A working example at: http://jsfiddle.net/AHv6c/ (source jquery code to display json response to a html table using append)
My problem is when some of the rows columns could have their own style class.
So I want to change some of the the table <th> to <th class='sampleStyle'> . Can you please let me know how should I change the java script to read the corresponding class from th and assign it to relevant columns (s).
Then the generated table should be something like:
<tr>
<td>56036</td>
<td class="sampleStyle">Deli</td>
....
By the way do you know better approach?
You may try something like http://www.jqversion.com/#!/Mdi8Kla
$.each(data, function(key, val) {
var tr = $('<tr></tr>'),
index = 0;
$.each(val, function(k, v){
$('<td>'+v+'</td>').addClass(
$('th:eq(' + index + ')').attr('class')
).appendTo(tr);
index++;
});
tr.appendTo('#display');
});
$("td:eq(0)", tr).addClass("sampleStyle");
before appending tr

Categories