Showing 0 to 0 of 0 entries in DataTable - javascript

Hi I am new and i am using dataTable to display my, mysql data.So My Data are display correctly but here my dataTable footer doesn't work correctly.
Here is my code
UI_CRUD.prototype.refreshTable = function(params = {}){
var tableBody = $('.view-datatable tbody');
var dataUrl = this.moduleURL+'/alenter code herel';
var title = this.moduleTitle;
// console.log(this.moduleTitle);
console.log('all ..');
$.ajax({
url: dataUrl,
data : params,
})
.done(function(data) {
var html = '';
$.each(data, function(index, item) {
html+= '<tr>';
$.each(item, function(index, data) {
(index != 'id') ? html+= '<td>'+data+'</td>' : html+='';
});
html+= '<td class="actions">' +
'<i class="icon-eye text-primary view-btn" data-id="'+item.id+'">'+
'</i>'+
'<span></span>'+
'<i class="icon-pencil7 text-primary edit-btn" data-id="'+item.id+'">' +
'</i>'+
'<span></span>'+
'<i class="icon-bin sweet_combine text-danger delete-btn" data-id="'+item.id+'">' +
'</i>'+
'</td>';
html+= '</tr>';
});
tableBody.html(html);
})
.fail(function(res) {
console.error(res,'UI_CRUD ERR : ');
});
}
This is the table in blade file.
<table class="table view-datatable" id="mytable">
<thead>
<tr>
<th>Company Code </th>
<th>Company Name </th>
<th>Company Address </th>
<th>Telephone No. </th>
<th>Fax No. </th>
<th style="text-align: center;">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
this is the laravel controller
public function getAll()
{
$company = $this->getCompanies();
return response()->json($company,200);
}
public function getCompanies()
{
$company = Company::select("id", "CO_COMCODE", "CO_NAME",
DB::raw("CONCAT(CO_ADD1, ',', CO_ADD2, ',', CO_ADD3, ',', CO_ADD4) AS Address"),
"CO_TELNO", "CO_FAXNO")
->get();
return $company;
}
This is response json
[{"id":39,"CO_COMCODE":"FFDE","CO_NAME":"dsfsdf","Address":"‌​fsdfsd,fsdf,fdsf,fsd‌​f","CO_TELNO":"12345‌​6789","CO_FAXNO":"12‌​3456789"},{"id":41,"‌​CO_COMCODE":"AAAA","‌​CO_NAME":"fdfdsf","A‌​ddress":"dsfdsf,dfds‌​f,dsffdsf,fdsfsd","C‌​O_TELNO":"123456789"‌​,"CO_FAXNO":"1234567‌​89"}]
This is My Output page
This is the response
JSon Response preview and
JSon Response

After many efforts, I fixed error
Issues was with applying dataTable plugin. After I remove that js file and add new dataTable.
<table class="table view-datatable">
<thead>
<tr>
<th>Company Code </th>
<th>Company Name </th>
<th>Company Address </th>
<th>Telephone No. </th>
<th>Fax No. </th>
</tr>
</thead>
<tbody></tbody>
var table = $('.view-datatable').DataTable( {
"processing" : true,
"retrieve": true,
"ajax" : {
"url" : ajax_url
},
"columns" : [ {
"data" : "CO_COMCODE"
}, {
"data" : "CO_NAME"
}, {
"data" : "Address"
}, {
"data" : "CO_TELNO"
}, {
"data" : "CO_FAXNO"
}, {
data: null,
className: "dataTable-center",
},],
"rowCallback": function( row, data, index ) {
$('td:eq(5)', row).html(
'<i class="icon-eye text-primary view-btn" data-id="'+data.id+'">'+
'</i>'+
'<span> </span>'+
'<i class="icon-pencil7 text-primary edit-btn" data-id="'+data.id+'">' +
'</i>'+
'<span> </span>'+
'<i class="icon-bin sweet_combine text-danger delete-btn" data-id="'+data.id+'">' +
'</i>'
);
},
"pagingType": "full_numbers",
buttons: {
buttons: [
{
extend: 'colvis',
className: 'btn btn-default'
},
{
text: 'Add New',
className: 'add-new btn bg-blue-800 ui-add-new',
action: function(e) {
// UI_addModel('show');
}
},
{extend: 'copy'},
// {extend: 'csv'},
{extend: 'excel'},
{extend: 'pdf'},
{extend: 'print'}
]
}
} );

Related

How can have multirows Footer in Datatables?

I want make two rows at my footer datatables. First row of footer for sum columns and second row of footer for search columns.
This is my code in javascript
$(function () {
$('#ntable1 tfoot th').each( function () { //for search columns in footer
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+'"/>' );
} );
var table = $("#ntable1").DataTable({
"responsive": false, "scrollX": true, "lengthChange": true, "autoWidth": false,
"buttons": [
{
extend: 'copy',
exportOptions: {
columns: [':visible' ]
}
},
{
extend: 'excel',
exportOptions: {
columns: [':visible' ]
},
messageBottom: textTop,
},
{
extend: 'print',
footer: true,
exportOptions: {
columns: [':visible' ]
},
messageTop: textTop
},
{
extend: 'colvis',
exportOptions: {
columns: [':visible' ]
}
}
],
footerCallback: function (row, data, start, end, display) { //for sum of columns in footer
var api = this.api();
// Remove the formatting to get integer data for summation
var intVal = function (i) {
return typeof i === 'string' ? i.replace(/[\$,]/g, '') * 1 : typeof i === 'number' ? i : 0;
};
// Total over all pages
total = api
.column(3)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
// Total over this page
pageTotal = api
.column(3, { page: 'current' })
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
// Update footer
$('tr:eq(0) td:eq(3)', api.table().footer()).html(format('$' + pageTotal + ' ( $' + total + ' total)')); //not work
// $(api.column(3).footer()).html('$' + pageTotal + ' ( $' + total + ' total)'); //not work
},
initComplete: function () {
// Apply the search
this.api().columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
}
}).buttons().container().appendTo('#ntable1_wrapper .col-md-6:eq(0)');
});
Datatables code in html
<table id="ntable1" class="table table-bordered table-striped">
<thead> ... </thead>
<tbody> ... </tbody>
<tfoot>
<tr> <!-- for sum columns -->
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr> <!-- for search columns -->
<th>No</th>
<th>Nama Program</th>
<th>Tahun</th>
<th>Jumlah Kota</th>
<th>Nama Kota</th>
<th>Jumlah Sekolah</th>
<th>Jumlah Siswa</th>
<th>Pre Test</th>
<th>Post Test</th>
<th>%</th>
<th>Tingkat Kepuasan</th>
<th>Tabungan Pelajar (Account)</th>
</tr>
</tfoot>
</table>
If I add row in footer, my search column doesn't work. My problem only how to have multiple rows in footer datatables, which first row for calculate sum and second row for search column. Hope anyone can help.

Javascript get specific data from data table with condition

I have a datatable like this
What I want is to get the latest notes with the corresponding shipment_id (the topmost notes) when clicking the copy summary report button above and paste it to some text editors for email template. But what I get is
Hi,
Below are the updates on the reimbursement requests for 3 shipment/s:
//first row
FBA15MQMW8BB: 23-Feb-21 06:08,PM Super Updated
23-Feb-21 06:06 PM :New Notes (updated) ----> not included
23-Feb-21 06:06 PM Invoice and BOL ----> not included
//2nd row
FBA15TX03JTX: 23-Feb-21 07:01 PM,Latest
23-Feb-21 07:01 PM New Notesss ----> not included
//3rd row
FBA15M1SQ8VH: 23-Feb-21 07:01 PM, Invoice and BOL
Will be sending updates again once I have additional information.
Thank you.
what i tried is
Swal.fire({
title: '<h2>Email Template copied to clipboard!</h2>',
icon: 'info',
html: '<p>You can now paste them anywhere completely.</p>',
confirmButtonText: 'Send Updates',
showCancelButton: true,
showCloseButton: true,
showLoaderOnConfirm: true,
preConfirm: (confirm) => {
var str='';
var emailBody='';
var count_shipments = $(".data-row").length;
var SearchFieldsTable = $("#tbl-inbound-shipments-in-progress tbody");
var trows = SearchFieldsTable.children(".data-row");
$.each(trows, function (index, row) {
var shipment_id=$(row).attr("data-shipment-id");
var notes = $(row).attr("data-notes");
//this is the code for copying the notes
str += shipment_id + ": " + (notes ? notes : "No notes") + "\n\n";
});
//the email body/template to be pasted
emailBody = 'Hi, \n\nBelow are the updates on the reimbursement requests for '+ count_shipments +' shipment/s: \n\n' + str +
'Will be sending updates again once I have additional information.\n\nThank you.'
var el = document.createElement('textarea');
el.value = emailBody;
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
},
EDIT: table structure and data fetch included as requested
<table class="table table-bordered table-striped table-hover display compact" id="tbl-inbound-shipments-in-progress" style="width:100%">
<thead class="text-primary">
<tr>
<th>#</th>
<th>{{ __('Client') }}</th>
<th>{{ __('SHIPMENT ID') }}</th>
<th>{{ __('Case ID') }}</th>
{{-- <th>{{ __('P/A/R') }}</th> --}}
<th>{{ __('Updated Date') }}</th>
<th>{{ __('Maturity') }}</th>
<th>{{ __('Action') }}</th>
</tr>
</thead>
</table>
table data
function load_inbound_shipment_in_progress() {
window.ISIP = $('#tbl-inbound-shipments-in-progress').DataTable({
//processing: true,
serverSide: true,
"fnInitComplete": function (oSettings, json) {
toastr.options.progressBar = true;
// toastr.info('Requested Inbound Shipment data is now loaded.');
$('#loading').hide();
},
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
iDisplayLength: 10,
ajax: "{{ route('admin.clients.inbound-shipment-in-progress', ['client'=>$client->id]) }}",
createdRow: function( row, data, dataIndex ) {
var red = ((data.maturity > 5) && (data.pending > 0)) ? 'bg-danger' : '',
notes = (data.notes!='') ? data.notes : '',
shipment_id = (data.shipment_id_nolink !='') ? data.shipment_id_nolink : '';
$(row).attr('data-row_id', data.id).attr('data-notes', notes).attr('data-shipment-id', shipment_id).attr('data-case_id', data.case_id).attr('data-pending', data.pending).attr('data-shipment_id', data.shipment_id).addClass(red);
$(row).addClass('data-row');
},
dom: 'lBfrtip<"actions">',
buttons: [
{
extend: 'copy',
className: 'btn btn-custom-summary',
text: 'Copy Summary Report',
action: function ( e, dt, node, config ) {
copyEmail();
}
}
],
columns: [
{ data: 'notes', name: 'notes', "class": "text-nowrap text-center", render: function(data) { return ''; }, fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
if (oData.notes != '') $(nTd).addClass('details-control');
}, orderable: false
},
{ data: 'client', name: 'client', "class": "text-nowrap text-center" },
{ data: 'shipment_id', name: 'shipment_id', "class": "text-nowrap text-center" },
{ data: 'case_id', name: 'case_id', "class": "text-nowrap text-center", render: function(data, type, full) {
console.log(this)
var link = ''+(data )+'';
return '<span class="link-mode-'+full.id+'">' + link + '</span><input style="display: none;" id="edit-mode" class="edit-mode-'+full.id+'" type="text" value="'+ data +'">' + ' <button onclick="popup_save_case_id(this)" id="edit-case-id" class="btn btn-primary btn-xs"> <i class="fas fa-edit"></i> Edit<input type="hidden" class="case_id" value="'+data+'"> </button>';
}},
// { data: 'p_a_r', name: 'p_a_r', "class": "text-nowrap text-center" },
{ data: 'updated_at', name: 'updated_at', "class": "text-nowrap text-center" },
{ data: 'maturity', name: 'maturity', "class": "text-nowrap text-center" },
{ data: 'action', name: 'action', "class": "text-nowrap text-center bg-light", orderable: false, searchable: false }
]
});
}

Add delete event inside delete button to each row of Datatables on Angular and add background-color into button

I am able to put a button inside each row of data tables but the button doesn't have any function, and I didn't know how to add delete event to that button. can someone help me? hope you give me the demo too ;)
*ps: also, how to put background-color on print, export button. className : red(on TS) and .red{ background-color : red;}(on CSS) didn't work out :/
*another ps : i'm using datatables.net
TS File
products: any = (data as any).default;
ngOnInit(): void {
this.dtOptions = {
ajax: {
url: '',
type: 'GET',
dataType: 'json',
},
columns: [
{
title: 'ID',
data: 'id',
},
{
title: 'Name',
data: 'name',
},
{
title: 'Gender',
data: 'gender',
},
{
title: 'Option',
data: null,
defaultContent:
'<button class="btn-delete type="button">Delete</button>',
targets: -1,
},
],
dom: 'Bfrtip',
buttons: [
{ extend: 'excel', text: 'Export' },
{
text: '<i class="fa fa-files-o"></i>',
action: function (e, dt, node, config) {
dt.ajax.reload();
},
},
{
extend: 'print',
text: 'Print',
},
],
};
}
html
<table
datatable
[dtOptions]="dtOptions"
class="mc row-border hover">
</table>
You can check this Demo
you need to rerender after delete process. You can add button like below and give function to it.
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of persons">
<td>{{ person.id }}</td>
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
<td><button class="btn-delete" (click)="deleterow(person)">Remove</button> </td>
</tr>
<tr *ngIf="persons?.length == 0">
<td colspan="4" class="no-data-available">No data!</td>
</tr>
</tbody>
</table>
in component you need rerender function
deleterow(person){
console.log(person);
//here do delete event
const that = this;
this.rerender()
}
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
this.dtTrigger.next();
});
}
and change your afterinit with
ngAfterViewInit(): void {
this.dtTrigger.next();
}

Get value of all checkbox selected in jQuery Datatables

I have the next Datatable
HTML
<table id="example" class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>Iden.</th>
<th>Nombres</th>
<th>Sel.</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Iden.</th>
<th>Nombres</th>
<th>Sel.</th>
</tr>
</tfoot>
</table>
JS
$('#example').DataTable({
scrollX: true,
deferRender: true,
"aaData": data.Data,
"columns": [{ data: "ID" },
{ data: "Identificacion" },
{ data: "Nombres" },
{ "data" : null,
"targets" : -1,
"orderable" : false,
"className" : "all",
"width" : "20px",
"render" : function(data, type, full) {
let texto = "";
texto = '<input type="checkbox" id="check_test" value="' + data.ID + '" />';
return texto;
}
}
]
});
I want get value of the selected checkboxes, so i tried this
var aux = [];
aux = $('#example tbody input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
however, this only obtains the values selected from the active page of the pagination datatable
How can I get the value of the selected checkboxes on all pages of datable?
Use $() DataTables API method to retrieve data from all pages, not just first page.
For example:
var $checkboxes = $('#example').DataTable().$('input[type=checkbox]:checked');

How to add index column to datatables

I'm trying to add an index column like this example ( https://datatables.net/examples/api/counter_columns.html ), in my table. I try to implement the code from the example to my program, but the results don't appear. How do I add an index column like the example, to my table ?
thank you
Table :
<table id="order_data">
<thead >
<tr >
<th style="text-align:center;" width="21%">Number</th>
<th style="text-align:center;" width="21%">Datetime </th>
<th style="text-align:center;" width="19%">Temp</th>
<th style="text-align:center;" width="21%">Humidity</th>
</tr>
</thead>
</table>
Javascript :
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#order_data').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
title: '<h3 align ="center">Monitoring</h3>',
text: '<i class="fa fa-pencil"></i>',
messageTop: '<p align ="center"><strong>PDF</strong> created by PDFMake with Buttons for DataTables.</p>'
},
{
extend: 'pdfHtml5',
customize: function (doc) {
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
},
title: 'Monitoring',
titleAttr: 'PDF',
text: 'PDF',
}
],
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]],
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
},
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#order_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
//$("#tabel").show();
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Both Date is Required");
}
});
dataTable.on( 'order.dt search.dt', function () {
dataTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
});
The example you're referencing isn't using server side processing. Rather it's assuming a static data source. You have serverSide: true and using an AJAX request to retrieve the data from a source so there are a couple of ways to handle this:
1) Use column render to generate the index value after the data is retrieved:
{
"sName": "Index",
"render": function (data, type, row, meta) {
return meta.row; // This contains the row index
}
}
2.) Add the index value to your data source and retrieve it along with your url:"fetch.php" request. Though this would actually act more like a unique ID and less like row numbering.
There is also an api call for row().index() that you could leverage in a number of ways.

Categories