Populating a DataTable with an object equal to an array of objects - javascript

I have a DataTable structured like the following:
<div class="table-responsive">
<table class="table table-striped table-condensed table-bordered" id="mainSutable2" style="width: 100%">
<thead>
<tr>
<th>Comment Time</th>
<th>ID</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
var mainSutable2 =$('#mainSutable2').DataTable({
paging: false,
ordering: true,
info: true,
oLanguage:{
sProcessing: 'No Data To Display', //change language of default "Processing" dialogue
sSearch: 'Filter'
},
data: trackingNotes,
columns: [
{ data: "ID" },
{ data: "comment" },
{ data: "dt" },
{ data: "status"}
]
});
I am trying to populate this table using the following: Please note MainSutable is another table that has a row that include the object value.
var trackingNotes = {};
trackingNotes = mainSutable.row(this).data().tracking_notes;
//tracikingNotes equals the following
/*
Object {tracking_note: Array[2]}
tracking_note: Array[2]
0:Object
ID: "12345"
comment: "yo"
dt: "2016-06-06 12:50:46.0"
guid: "9999"
status: "1"
1:Object
ID: "12346"
comment: "hey"
dt: "2016-06-08 12:50:46.0"
guid: "9999"
status: "2"
*/
If anyone has any tips of information that could lead me in the right direction, it would be greatly appreciated.

Not sure why it's not working on your side. I've tried replicating the problem but it's working for me and the data is displayed in the DataTable maybe there's an issue with the script references to dataTable.js or maybe you're not calling the binding logic inside the document load.
Copy and paste the example below in a new page and run it, you will see that it works.Figure out what's different in your code compared to mine and I'm sure it will help you solve the problem:
<head runat="server">
<title></title>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script>
$(function () {
var trackingNotes = [];
var note1 = { ID: "1", comment: "comment1", dt: new Date(), guid:"1", status: "1" };
var note2 = { ID: "2", comment: "comment 2", dt: new Date(), guid: "2", status: "1" };
var note3 = { ID: "3", comment: "comment 3", dt: new Date(), guid: "3", status: "0" };
trackingNotes.push(note1);
trackingNotes.push(note2);
trackingNotes.push(note3);
var mainSutable2 = $('#mainSutable2').DataTable({
paging: false,
ordering: true,
info: true,
oLanguage: {
sProcessing: 'No Data To Display', //change language of default "Processing" dialogue
sSearch: 'Filter'
},
data: trackingNotes,
columns: [
{ data: "ID" },
{ data: "comment" },
{ data: "dt" },
{ data: "status" }
]
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="table-responsive">
<table class="table table-striped table-condensed table-bordered" id="mainSutable2" style="width: 100%">
<thead>
<tr>
<th>Comment Time</th>
<th>ID</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>

Related

load json data in bootstrap data table

i created a table using html . now i want to populate my table using json data. i have been using the example https://www.youtube.com/watch?v=A20PY5RxdI8
my javascript code is here
$(document).ready(function () {
$.getJSON("my.php", function(json){
myjson = json;
}).done(function() {
$('#tble').bootstrapTable('load', myjson);
var $table = $('#tble');
$table.bootstrapTable('load', myjson);
$table.bootstrapTable({
search: true,
pagination: true,
buttonsClass: 'primaryt',
showFooter: true,
minimumCountColumns: 2,
columns: [ {
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}],
data: myjson
});
});
});
<table id = 'tble'>
<tr class=xl70 height=42 style='mso-height-source:userset;height:31.5pt'>
<th height=42 class=xl72 width=57 style='height:31.5pt;border-top:none;
border-left:none;width:43pt' data-field="one">1</th>
<th class=xl72 width=80 style='border-top:none;border-left:none;width:60pt'>2</th>
<th class=xl72 width=97 style='border-top:none;border-left:none;width:73pt'>3</th>
</tr>
</table>
i want to populate json into my table but it does not display any data in the said table
You can use the following code example:
$.getJSON("my.php")
.done(function(data) {
$('#tble').bootstrapTable('load', data);
})
Read the $.getJson() documentation for more example.
I have checked the documentation of Bootstrap table which you are using in your example.
The document is poorly written without explaining the parameters. Which results in confusion. When you read the document and do some JS fiddle you will realise that data-toggle attribute is very important. The value of this attribute should be the same as the Id of your table.
you can try removing data attribute filed in below fiddle to verify it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.css" rel="stylesheet">
<script src="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.js"></script>
<div id="toolbar">
<button id="button" class="btn btn-secondary">load</button>
</div>
<table
id="table"
data-toggle="table"
data-height="460">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="name">Item Name</th>
<th data-field="price">Item Price</th>
</tr>
</thead>
</table>
<script>
var $table = $('#table')
var $button = $('#button')
function randomData() {
var startId = ~~(Math.random() * 100)
var rows = []
for (var i = 0; i < 10; i++) {
rows.push({
id: startId + i,
name: 'test' + (startId + i),
price: '$' + (startId + i)
})
}
return rows
}
$(function() {
var someData = randomData();
debugger;
$table.bootstrapTable('load', someData)
})
</script>
You will need to modify your code as below.
HTML
<table id = 'tble' data-toggle="tble">
<thead>
<tr>
<th data-field="one">ID</th>
<th data-field="two">f name</th>
<th data-field="three">last name</th>
</tr>
</thead>
</table>
and JS
$(document).ready(function () {
$('#table').bootstrapTable({
url: 'my.php',
pagination: true,
search: true,
columns: [{
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}]
})
});
Note: your URL should return a json response. Else instead of getJSON you can use $.ajax

Datatables - Full row data editor not working

I am trying full row editor functionality of data-tables.
Editor buttons are not coming.
Without that editor modal will not get displayed.
Inline editor is enabling the columns to edit but its not changing the value of the column.
JS code for data-table.
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "resources/data/data.txt",
table: "#NACH-User-Table",
idSrc: 'id',
fields: [ {
label: "User ID:",
name: "UserID"
}, {
label: "Name:",
name: "Name"
}, {
label: "Email ID:",
name: "emailID"
}, {
label: "Role:",
name: "Role"
}, {
label: "Status:",
name: "Status"
}
]
} );
$('#NACH-User-Table').on( 'click', 'tbody td:not(:first-child)', function (e) {
editor.inline( this, {
submit: 'allIfChanged'
} );
} );
$('#NACH-User-Table').DataTable({
"ajax" :"resources/data/data.txt",
select: {
style: 'os',
selector: 'td:first-child'
},
ordering: true,
"dom": 'B<"top"fl>rt<"bottom"ip><"clear">',
button: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
"columns": [
{
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ "data": "UserID"},
{ "data": "Name" },
{ "data": "emailID"},
{ "data": "Role"},
{ "data": "Status"}
]
});
});
<table id="NACH-User-Table" class="table table-striped table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th></th>
<th>UserID</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
</tr>
</thead>
</table>
Libraries Included
<script src="./resources/DataTables/jQuery-3.3.1/jquery-3.3.1.min.js"> </script>
<script src="./resources/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="./resources/DataTables/datatables.min.js"></script>
<script src="./resources/DataTables/DataTables-1.10.18/js/jquery.dataTables.min.js"></script>
<script src="./resources/DataTables/DataTables-1.10.18/js/dataTables.bootstrap4.min.js"></script>
<script src="./resources/DataTables/Buttons-1.5.4/js/dataTables.buttons.min.js"></script>
<script src="./resources/DataTables/Buttons-1.5.4/js/buttons.bootstrap4.min.js"></script>
<script src="./resources/DataTables/Buttons-1.5.4/js/buttons.print.min.js"></script>
<script src="./resources/DataTables/Responsive-2.2.2/js/dataTables.responsive.min.js"></script>
<script src="./resources/DataTables/Responsive-2.2.2/js/responsive.bootstrap4.min.js"></script>
<script src="./resources/DataTables/Editor-1.8.1/js/dataTables.editor.min.js"></script>
<script src="./resources/DataTables/Editor-1.8.1/js/editor.bootstrap4.min.js"></script>
All the required CSS are Included as well.

Two footers not printed in pdf and excel format when clicked in button in jquery datatable

Actaullay I have buttons to save in pdf and excel format.I have two footers coming from json as Total and Percentage.When i click the Button then only Total footer is coming but the Percentage row is not coming in the pdf and excel files.I need to show both the footer but it is not coming.
<table id="report46Table" class="display responsive nowrap" style="width: 100%">
<thead>
<tr>
<th>Disturbance</th>
<th>Zero</th>
<th>Minor</th>
<th>Medium</th>
<th>Major</th>
<th>Total</th>
<th>Occurance</th>
</tr>
</thead>
<tfoot>
<tr id="fTotal">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr id="fPercentage">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
script to load the datatable is:
<script>
$(document).ready(function() {
var report46Data = [];
var report46Footer = null;
var report46Table = $('#report46Table').DataTable({
data : report46Data,
dom: 'Bfrtip',
buttons: [
'copy',
{
extend: 'excel',
footer: true,
text : 'Export to Excel',
messageTop: 'Records of forest disturbances in the forest',
filename: function(){
return 'report46';
},
},
{
extend: 'pdfHtml5',
footer: true,
//orientation : 'landscape',
pageSize: 'TABLOID',
text : 'Export to Pdf',
messageTop: 'Records of forest disturbances in the forest',
title: '',
filename: function(){
return 'report46';
},
},
],
ordering: false,
"paging" :false,
columns : [ {
"data" : "disturbanceName"
}, {
"data" : "iZero"
}, {
"data" : "iMinor"
}, {
"data" : "iMedium"
} ,{
"data" : "iMajor"
},{
"data" : "total"
},{
"data" : "occurance"
}],
"footerCallback" : function(row, data, start, end, display) {
var api = this.api();
if (report46Footer) {
$($("#fTotal")[0].cells[0]).html(report46Footer[0].disturbance);
$($("#fTotal")[0].cells[1]).html(report46Footer[0].iZero);
$($("#fTotal")[0].cells[2]).html(report46Footer[0].iMinor);
$($("#fTotal")[0].cells[3]).html(report46Footer[0].iMedium);
$($("#fTotal")[0].cells[4]).html(report46Footer[0].iMajor);
$($("#fTotal")[0].cells[5]).html(report46Footer[0].total);
$($("#fTotal")[0].cells[6]).html("");
$($("#fPercentage")[0].cells[0]).html(report46Footer[1].disturbance);
$($("#fPercentage")[0].cells[1]).html(report46Footer[1].iZero);
$($("#fPercentage")[0].cells[2]).html(report46Footer[1].iMinor);
$($("#fPercentage")[0].cells[3]).html(report46Footer[1].iMedium);
$($("#fPercentage")[0].cells[4]).html(report46Footer[1].iMajor);
$($("#fPercentage")[0].cells[5]).html(report46Footer[1].total);
$($("#fPercentage")[0].cells[6]).html("");
}
}
});
$.ajax({
url : A_PAGE_CONTEXT_PATH + "/api/report46/all",
method : "GET",
dataType : "json",
success : function(response) {
report46Data = response.dataList;
report46Footer = response.footer;
report46Table.rows.add(report46Data).draw();
}
});
});
</script>

Best Practice to Lazy Load Huge Data into a Table

I have a fiddle that make an AJAX to get this Data to render a table. My goal is load only 10 rows during the first initial page load.
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Account ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
</table>
JavaScript
$(document).ready(function() {
$('#example').DataTable( {
"bPaginate": true,
"processing": true,
"bServerSide": true,
ajax: {
url: 'https://api.myjson.com/bins/1egsx',
dataSrc: 'data'
},
columns: [
{ data: 'account_id' },
{ data: 'name' },
{ data: 'email' }
],
"deferRender": true,
"deferLoading": 10,
} );
});
I've been trying to use datatables JavaScript plug-in, but it doesn't seem to work.
Are there any other scripts/plug-ins/frameworks I should look into?

Unable to display data using jQuery datatables, AJAX and JSON

I'm having a problem displaying my data on my jQuery DataTable using AJAX. I'm using the library from datatables.net. I've tried packaging the JSON in many different formats and nothing is working. I've also messed around with the 'columns' section, interchanging 'title' and 'data.' I only have one event to display for now, but the bottom of the table shows something crazy like 4,000 entries. Here is my code:
<script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/api/EventsApi/GetAll",
"dataSrc": ""
},
columns: [
{ title: "Title" },
{ title: "Template" },
{ title: "Capacity" },
{ title: "Boarding Location" },
{ title: "Status" },
{ title: "Edit / Delete" }
//{ "data": "title" },
//{ "data": "eventTemplateID" },
//{ "data": "locomotive.capacity" },
//{ "data": "boardingLocationStart.city" },
//{ "data": "status" },
//{ "data": "status" }
]
});
});
<div class="title-content">#ViewBag.Title</div>
<div id="dataTable">
<table id="myTable" class="table table-hover" style="text-align: center;">
<tbody id="tBody">
<!-- Table body data goes here -->
</tbody>
</table>
</div>
Here is the JSON that's being returned from the AJAX call:
{"data":[{"tripEventID":1,"extraDetails":"this train has special details","eventName":"ZombieTrainEventName ","departureDate":"\/Date(1443715200000)\/","returnDate":"\/Date(1443718800000)\/","eventCapacityOveride":100,"eventTemplateID":3,"title":"The Zombie Train ","companyID":1,"description":"description of zombie train ride ","boardingClosed":30,"status":1,"boardingLocationStart":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationStartTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnFrom":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"allowFlexableReturnDate":false,"product":[],"productBundle":[{"bundleID":10,"companyID":1,"displayName":" Pumkin Bundle copy Test","price":0.0100,"tax":0.0200,"productList":[]}],"locomotive":{"trainID":1,"companyID":1,"title":"Skunk_Steam ","type":1,"description":"Steam locomotive ","capacity":998,"status":0},"media":{"mediaID":1,"companyID":1,"hero":[],"gallery":[{"mediaDetailID":6,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":null,"url":null},{"mediaDetailID":7,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":"path6","url":"url6"},{"mediaDetailID":8,"formatTypeID":2,"fileName":"testimage7.txt","order":1,"path":"path7","url":"url7"}],"inside":[{"mediaDetailID":1,"formatTypeID":1,"fileName":"testimage.txt","order":1,"path":null,"url":null},{"mediaDetailID":2,"formatTypeID":1,"fileName":"testimage2.txt","order":1,"path":null,"url":null},{"mediaDetailID":3,"formatTypeID":1,"fileName":"testimage3.txt","order":1,"path":null,"url":null}]},"duration":15,"isExclusive":false,"timeAtDestination":45,"isOneWay":false}]}
Like I said, I've tried repackaging the JSON as nested objects and arrays with nothing working. Am I missing something obvious? Any help is appreciated, thank you!
You have to name the columns in your js like the json index keys like this:
$(document).ready(function() {
$('#myTable').DataTable( {
"ajax": "path/to/your/file.json",
"columns": [
{ "data": "title" },
{ "data": "eventTemplateID" },
{ "data": "eventCapacityOveride" },
{ "data": "boardingLocationStart.streetAddress" },
{ "data": "status" },
{ "data": null }
],
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
} );
Note that you can define custom data in tables with the columnDefs option.
And than edit your HTML with something like this:
<table id="myTable" class="table table-hover" style="text-align: center;">
<thead>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</tfoot>
</table>
Here you can find a working fiddle

Categories

Resources