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

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>

Related

Having problems with importing html tables to Tabulator

I have recently switched from Tabulator 4.5 to 5.0 and I am having some problems with my old code. I used to just give existing Drupal HTML tables a Tabulator skin, however, now while the tables are generated, the data is lost, and no rows are displayed. Here is an example:
HTML
<table data-drupal-selector="edit-cimek" class="responsive-enabled table table-hover table-striped" id="edit-cimek"
data-striping="1">
<thead>
<tr>
<th>Hivatalos név</th>
<th>Címtípus</th>
<th>Teljes cím</th>
<th>Kontakt</th>
<th>Gombok</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>AAAAAAAAAAAAAAAAAAAA</td>
<td>BBBBBBBBBB</td>
<td>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</td>
<td>DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD</td>
<td><a id='cimtorol_5' class='cimtorol'><img title='Törlés'
src='/src/here' alt='Törlés' width='30px'></a> <a
id='cimmodosit_5' class='cimmodosit'><img title='Módosítás'
src='/src/here' alt='Módosítás' width='30px'></a>
</td>
</tr>
<tr class="even">
<td>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</td>
<td>BBBBBBBBB</td>
<td>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</td>
<td>D</td>
<td><a id='cimtorol_1' class='cimtorol'><img title='Törlés'
src='/src/here' alt='Törlés' width='30px'></a> <a
id='cimmodosit_1' class='cimmodosit'><img title='Módosítás'
src='/src/here' alt='Módosítás' width='30px'></a>
</td>
</tr>
</tbody>
</table>
JS
var table = new Tabulator("#edit-cimek", {
columns: [
{ title: Drupal.t('Official name'), field: "name", sorter: "string" },
{ title: Drupal.t('Address type'), field: "type", sorter: "number" },
{ title: Drupal.t('Full address'), field: "address", sorter: "string" },
{ title: Drupal.t('Contact'), field: "kapcstarto", sorter: "number" },
{
title: Drupal.t('Buttons'), field: "buttons", sorter: "string", formatter: "html", cellClick: function (e, cell) {
e.preventDefault();
}
}
]
});
What might be the problem, and why doesn't it work in 5.0 when it worked in 4.5?

datatable column filtering with serverside(ajax) doesn't work (with django)

I'm developing with django and javascript with datatable.
I want to apply column filtering in my datatable
(https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html)
but it works fine without serverside option & ajax (in client side),
but it doesn't work with serverside option & ajax.
How can i FIX IT? Please help me..
this is my code.
<table id="sample_table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="sample_id">ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</thead>
<tbody id="sample_table_body">
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
var column_list = [
{ "data" : "id" , "className": "sample_id"},
{ "data" : "receiving_at" },
{ "data" : "serialnumber" },
{ "data" : "name" },
{ "data" : "birthday" },
];
$('#sample_table tfoot th').each(function(){
var title = $("#sample_table thead th").eq( $(this).index() ).text();
$(this).html('<input type="text" placeholder="Search '+title+'" />' );
});
var sample_table = $('#sample_table').DataTable({
"paging": true,
"autoWidth": false,
"lengthChange": false,
"ordering": true,
"processing" : true,
"columns": column_list,
"order": [ [0, 'desc'] ],
"fixedHeader": true,
"orderCellsTop": true,
"ajax": {
url: '/view_datatable/',
type: 'POST'
},
"serverSide" : true, //get data from server
"initComplete": function() { // column filtering RUN after table loaded .
$( '#sample_table tfoot input' ).on( 'keyup change clear', function () {
if ( sample_table.search() !== this.value && this.value.length>0) {
search_result = sample_table.search( this.value );
search_result.draw();
}
} );
}
});
#view.py
def list_datatable(request, companyname):
context = {}
if(request.method == "POST"):
start_page = int(request.POST['start'])
order_direction = request.POST["order[0][dir]"] # direction of ordering(asc, desc)
order_col_no = request.POST["order[0][column]"] # number of index to sort
order_col_name = request.POST['columns[' + str(order_col_no) + '][data]'].strip() # name of colum of ordering
sample_list_all = Sample.objects.all().order_by(order_col_name)
sample_list_per_page = []
for idx, obj in enumerate(sample_list_all[start_page:start_page + 10]):
data = {}
data['id'] = obj.id
data['receiving_at'] = str(obj.receiving_at)
data['birthday'] = obj.birthday
data['serialnumber'] = obj.serialnumber
data['name'] = obj.name
sample_list_per_page.append(data)
#-- end of --#
datalist_to_json = json.dumps(
{"data": sample_list_per_page, "recordsFiltered": len(sample_list_all), "recordsTotal": len(sample_list_all)}
)
return HttpResponse(datalist_to_json, content_type="application/json")

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

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