How to access additional data in JSON requested by Dynatable AJAX call - javascript

I am using the dynatable.com plugin to create a table of of schools that are stored in our database. The table can be filtered so does not always show the total number of schools. We do not display a 'number of pupils' column but are trying to show a 'total number of pupils' summary at the bottom of the table.
html on the page is as follows:
<table id="dynatable">
<thead>
<tr>
<th data-dynatable-column="id">ID</th>
<th data-dynatable-column="schoolName">School Name</th>
<th data-dynatable-column="contactName">Contact Name</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="3"><span id="numPupils"></span> Pupils</td>
</tr>
</tfoot>
</table>
Followed by the JS:
<script>
$('#dynatable').dynatable({
dataset: {
ajax: true,
ajaxUrl: '/my/json/page.json',
ajaxOnLoad: true,
records: []
}
});
</script>
And a sample of the JSON retrieved (note the additional totalNumPupils field at the bottom):
{
"records": [
{
"id": "1",
"schoolName": "ABC School",
"contactName": "Terry"
},
{
"id": "17",
"schoolName": "DEF School",
"contactName": "Claire"
},
{
"id": "45",
"schoolName": "GHI School",
"contactName": "Barry"
}
],
"queryRecordCount": 3,
"totalRecordCount": 450,
"totalNumPupils": 794
}
I am trying to establish if there is a way to access the responseJSON.totalNumPupils that is requested by dynatable's ajax call or whether I would have to perform my own ajax call, ascertain the number of pupils, then pass in the JSON to the dynatable function afterwards?

Please see the code snippet. You can use normal AJAX to get the JSON payload, then populate the dynatable with the data from the AJAX response, while simultaneously accessing the unique totalNumPupils property.
$('#dynatable').dynatable({
dataset: {
ajax: true,
ajaxUrl: 'https://api.myjson.com/bins/1ezw8l',
ajaxOnLoad: true,
records: []
}
});
$.ajax({
url: 'https://api.myjson.com/bins/1ezw8l',
success: function(data) {
$('#dynatable').dynatable({
dataset: {
ajax: false,
records: data
}
});
$('#numPupils').text("Total Pupils: " + data.totalNumPupils);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.css" rel="stylesheet" />
<table id="dynatable">
<thead>
<tr>
<th data-dynatable-column="id">ID</th>
<th data-dynatable-column="schoolName">School Name</th>
<th data-dynatable-column="contactName">Contact Name</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="3"><span id="numPupils"></span> Pupils</td>
</tr>
</tfoot>
</table>

Related

Footnotes at the bottom of Datatables

My table looks like the following:
And basically I just want a row below the table indicating what the small red 1 and 2 means on their respective rows. I cannot find anything online to do with comments or footnotes in datatables. And I have tried to use the tfoot tag and append it to that but it looks awful (which I assume is datatables not agreeing with that method). Anyone know a solution for this?
HTML:
<table id="'.$id.'" class="table table-bordered dt-responsive" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
<thead>
<tr>'.$tableHeadings.'</tr>
</thead>
<tbody>
'.$tableContent.'>
</tbody>
<tfoot>
<td>A note here explaining something important.</td>
</tfoot>
</table>
Javascript:
$(function() {
let table;
table = $('#table_preview').DataTable({
"pageLength": 25,
"processing": true,
"ajax": {
"url": '/assets/ajax/table_ajax_handler.php',
"type": "POST",
"data": { action: "getPesticidesForTable" }
},
"columns": [
{ "data": "crop" },
{ "data": "diseases" },
{ "data": "chemical" },
{ "data": "product" },
{ "data": "rate" },
{ "data": "max_no" },
{ "data": "hi" },
{ "data": "mrl" },
{ "data": "pcs_no" },
{ "data": "supplier" }
],
"searchCols": [
{ "search": '<?=$crop?>' || null },
{ "search": '<?=$disease?>' || null }
],
"columnDefs" : [
{
"targets": [0],
"visible": false,
"searchable": true
},
{
"targets": [1],
"visible": false,
"searchable": true
}
],
"order": [[ 2, "asc" ]],
"rowsGroup": [2, 4, 5, 6, 7, 8, 9]
});
});
You can include a <tfoot> section in the HTML, and then use a colspan to allow the text to extend beyond the first column.
For example, assuming a table with 6 columns:
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office in Country</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
...
</tbody>
<tfoot>
<tr>
<td colspan="2">A note here explaining something important.</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
This looks like the following:
If your text might expand the full width of the footer, then you can use this:
<tfoot>
<tr>
<td colspan="6">A very much longer note here explaining something extremely important.</td>
</tr>
</tfoot>
The number of cells in the footer (also accounting for any colspans) must match the number of cells in a row.
Background note - there are some limitations to using colspans in DataTables. See complex headers for more information.

How to multiply and Sum 2 columns of datatables using jquery? - Datatables

I want to show the result by using JQuery
I'm using dataTables library for table to show the result. I want to apply following computation on 2 columns using datatables jquery or ajax like
I have two arrays var arr1 = [2,3,4,5]; and var arr2 = [4,3,3,1];
(4*2+3*3+4*3+5*1) Total=34
Using DataTables for this table
This is the pic of table result format i want to show like.
$(document).ready(function() {
var t = $('#example').DataTable({
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0
}],
"order": [
[1, 'asc']
]
});
t.on('order.dt search.dt', function() {
t.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<table width="100%" class="display" cellspacing="0" id="example">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
<th>Current Sales * 1.5</th>
<th>(-) Closing Balance</th>
<th>Current Order</th>
<th>Distributor</th>
<th>Date</th>
</tr>
</thead>
</table>
jsfiddle
$(document).ready(function() {
// multiply nsp and closing balance
$.each(dataSet, function(i, row) {
row.total = row.nsp * row.closing_balance;
});
// Table definition
var dtapi = $('#example').DataTable({
data: dataSet,
"deferRender": false,
"footerCallback": function(tfoot, data, start, end, display) {
var api = this.api();
// adding product of nsp and closing_balance
// here column 5 contains product so change it
// accordingly
var p = api.column(5).data().reduce(function(a, b) {
return a + b;
}, 0)
$(api.column(5).footer()).html(p);
$("#total").val(p);
},
"order": [1],
"columns": [
// rest of the columns
{
data: "id"
}, {
data: "product_name"
}, {
data: "nsp"
}, {
data: "closing_balance",
}, {
data: "date",
}, {
data: "total"
}
]
});
});
// DataTable data set used
var dataSet = [{
"id": "Airi",
"product_name": "Satou",
"nsp": 230,
"closing_balance": 23,
"date": "28th Nov 08",
}, {
"id": "Angelica",
"product_name": "Ramos",
"nsp": "191",
"closing_balance": 131,
"date": "9th Oct 09",
}, {
"id": "Ashton",
"product_name": "Cox",
"nsp": 191,
"closing_balance": 37,
"date": "12th Jan 09",
}];
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<table class="display" id="example">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>NSP</th>
<th>Closing Balance</th>
<th>Date</th>
<th>NSP * Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>NSP</th>
<th>Closing Balance</th>
<th>Date</th>
<th>NSP * Closing Balance</th>
</tr>
</tfoot>
<tbody></tbody>
</table>
<label>Total</label>
<input type="text" id="total" class="form-control" readonly value="0.0" />

Howto use Boostrap table to get column sum using external json file

I have the following bootstrap based table and I am trying to calculate the total MarketValue. Its reading an external json file. but for some reason its not adding the values.
the problem starts when i load an external json. file. How can i fix this?
$.getJSON("json/prep.json", function (jsonFromFile) {
$('#table1').bootstrapTable({
data: jsonFromFile.rows
})
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue);
}, 0);
document.querySelector('.total1').innerHTML = total1;
});
JSON - prep.json
{
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "1000",
"MaxApprovedLoanAmt": "10000",
"LoanBalance": "1849000",
"AvailableCredit": "2877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "oJohnson",
"ContactPhone": "-3614",
"RiskCategory": "Yellow",
"rows": [{
"Account": "086-1234",
"ClientName": "S Smth",
"AccountType": "tail",
"LongMarketValue": "$40000"
}, {
"Account": "086-1235",
"ClientName": "all Sth",
"AccountType": "REV Trust",
"LongMarketValue": "$55000"
},
{
"Account": "086-1236",
"ClientName": "Sly Smith",
"AccountType": "Reail",
"LongMarketValue": "$5500"
}]
}
HTML
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="MarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>
data is undefined in your code, you have to retrieve data from table or from Json. Also your data returns a string with $ sign, so you have to remove it before parsing it.
Here is a working example.
// Code goes here
$(function () {
$.getJSON("https://api.myjson.com/bins/89vsf", function (jsonFromFile) {
$('#table1').bootstrapTable({
data: jsonFromFile.rows
})
var data = $('#table1').bootstrapTable('getData');
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue.replace('$',''));
}, 0);
document.querySelector('.total1').innerHTML = total1;
});
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="LongMarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.js"></script>
<script src="script.js"></script>
</body>
</html>
Here is a working plunker of the code. http://plnkr.co/edit/PSCR5iS7DSWkuQb1jv5P?p=preview
Hope this helps.

DataTables warning: table id=example - Requested unknown parameter '1' for row 1, column 1

Getting error "DataTables warning: table id=example - Requested unknown parameter '1' for row 1, column 1. For more information about this error, please see http://datatables.net/tn/4" while loading the data from ajax api call the json received from the back end is as below
[{"CustomerName":"Dinesh","product":"23234","perticulars":"wrwer","AddressOfCustomer":"wrew`","ContactNumbers":"jhkjhb"}, {"CustomerName":"dd","product":"dfsdfs","perticulars":"fsdfs","AddressOfCustomer":"sdfsdf","ContactNumbers":"fsfsf"}, {"CustomerName":"Pratik","product":"toothbrush","perticulars":"6 inch","AddressOfCustomer":"shreedhama white rose","ContactNumbers":"9949634396"}]
Snippet of HTML div tag for which table data is being populated is as below.
<table id="example" class="display" align="center" vertical-align="middle"; cellspacing="0" width="100%">
<thead>
<tr>
<th>Customer Name</th>
<th>Product</th>
<th>Perticulars</th>
<th>Address of customer.</th>
<th>Contact number</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Customer Name</th>
<th>Product</th>
<th>Perticulars</th>
<th>Address of customer.</th>
<th>Contact number</th>
</tr>
</tfoot>
</table>
Below is the ajax call I am doing and in success function trying to populate data from the json
$.ajax({
url:'AddQuotation',
type:'get',
success:function(data){
alert(data);
var resultTable = $('#example').DataTable({
"columns": [
{ data: "CustomerName" },
{ data: "product" },
{ data: "perticulars" },
{ data: "AddressOfCustomer" },
{ data: "ContactNumbers" }
],
"destroy": true,
"dom": 'lrtip'
} );
resultTable.rows.add(data1).draw();
dataSet = data;
},
error:function(){
alert('error');
}
});
You need to have data object that includes your array of objects.
{"data": [{"CustomerName":"Dinesh","product":"23234","perticulars":"wrwer","AddressOfCustomer":"wrew`","ContactNumbers":"jhkjhb"}, {"CustomerName":"dd","product":"dfsdfs","perticulars":"fsdfs","AddressOfCustomer":"sdfsdf","ContactNumbers":"fsfsf"}, {"CustomerName":"Pratik","product":"toothbrush","perticulars":"6 inch","AddressOfCustomer":"shreedhama white rose","ContactNumbers":"9949634396"}]}
A working DEMO.
In my case I just changed the following in my code and the error
DataTables warning: table id=bootstrap-data-table2 - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
was gone:
From:
<tbody>
#foreach (var item in Model.HRMS_Tbl_ExpenseClaimModelList)
{
<tr>
#if (item.Approved == "1")
{
<td>#item.Date</td>
<td>#item.Date</td>
<td>#item.Type</td>
<td>#item.Amount</td>
}
</tr>
}
</tbody>
To:
<tbody>
#foreach (var item in Model.HRMS_Tbl_ExpenseClaimModelList)
{
if (item.Approved == "1")
{
<tr>
<td>#item.Date</td>
<td>#item.Date</td>
<td>#item.Type</td>
<td>#item.Amount</td>
</tr>
}
}
</tbody>

Generating diff view using ng-repeat

I have a json containing revision/history info of modified entity which holds its old and new values. Diff is generated with https://github.com/benjamine/jsondiffpatch and I've done additional parsing myself to form final json format to be rendered.
Example data:
[
{
"createdBy": "admin#localhost",
"modifiedAt": 1445113889873,
"left": [
{
"Status": "Open"
}
],
"right": [
{
"Status": "In Progress"
}
]
},
{
"createdBy": "admin#localhost",
"modifiedAt": 1445114315786,
"left": [
{
"Description": "hello"
},
{
"Assignee": "Uncle Bob (test#test)"
}
],
"right": [
{
"Description": "bye"
},
{
"Assignee": "Willy Wonka (willy#hello)"
}
]
}
]
I am looking a nice way to form a table for this where for each revision I get separately left and right columns and values on separate rows. Probably tired, but I can't figure out how would ng-repeat work for this:
<div ng-repeat="(key, value) in vm.revisions | orderBy:'-modifiedAt'">
<table class="table">
<thead>
<tr>
<th width="20%">Field</th>
<th width="40%">Old Value</th>
<th width="40%">New Value</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
I am hoping for result like this:
Thanks in advance!
If I am right about data format:
<div ng-repeat="revision in vm.revisions | orderBy:'-modifiedAt'">
<table class="table">
<thead>
<tr>
<th width="20%">Field</th>
<th width="40%">Old Value</th>
<th width="40%">New Value</th>
</tr>
</thead>
<tbody ng-repeat="(index, left) in revision.left">
<tr ng-repeat="(field, leftValue) in left">
<td>{{field}}</td>
<td>{{leftValue}}</td>
<td>{{revision.right[index][field]}}</td>
</tr>
</tbody>
</table>
</div>
See it on jsfiddle: http://jsfiddle.net/q6zqgfr8/

Categories