issue with datatable with columnFilter.js - javascript

I have problem with datable server side after columns Filter or pagination. Firstly, after reload page - all fine, data get correctly. But after then i sorting or filtering columns, request url return error.
Here is my jquery:
var customer_id = $('input[name=customer-id]').val();
// Data tables
$('#customers-list-data').DataTable({
processing: true,
serverSide: true,
ajax: '/customers/edit/'+customer_id,
columns: [
{ data: 'first_name', name: 'first_name' },
{ data: 'last_name', name: 'last_name' },
{ data: 'phone', name: 'phone' },
{ data: 'country', name: 'country' },
{ data: 'city', name: 'city' },
{ data: 'address', name: 'address' },
{ data: 'email', name: 'email' },
{ data: 'action', name: 'action', orderable: false, searchable: false}
],
pagingType: 'full_numbers',
dom: '<"dt-top-row"Bfl>r<"dt-wrapper"t><"dt-row dt-bottom-row"<"row"<"col-sm-6"i><"col-sm-6 text-right"p>>>',
buttons: [
{
extend: 'collection',
text: 'Save <span class="caret" />',
buttons : ['csvFlash', 'excelFlash', 'pdfFlash']
},
'colvis'
]
});
$('#customers-list-data').dataTable().columnFilter({
sPlaceHolder: "head:after",
aoColumns: [
{ type: "text" },
{ type: "text" },
{ type: "text" },
{ type: "text" },
{ type: "text" },
{ type: "text" },
{ type: "text" },
null
]
});
And this is method on laravel project:
public function getEdit(Request $request, Customer $customer)
{
if($request->ajax()) {
$customer_data = $customer->Data()->get();
return Datatables::of($customer_data)
->addColumn('action', function ($customer_data) {
return '<div class="btn-group">
<i class="fa fa-edit"></i>
<i class="fa fa-times"></i>
</div>';
})
->make(true);
}
}
First time request url :
http://address.com/customers/edit/39?draw=1&columns%5B0%5D%5Bdata%5D=first_name&columns%5B0%5D%5Bname%5D=first_name ...
After filtering or sorting, pagination:
http://address.com/customers/edit/39?draw=2&columns=%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D&order=%5Bobject+Object%5D&start=10&length=10&search=%5Bobject+Object%5D&sRangeSeparator=~
Laravel debug error:
in Request.php line 78
at HandleExceptions->handleError('2', 'Illegal string offset 'column'', '/var/www/dev/vendor/yajra/laravel-datatables-oracle/src/yajra/Datatables/Request.php', '78', array('orderable' => array(), 'i' => '0', 'c' => '1')) in Request.php line 78
Here is my table:
<table id="customers-list-data" class="table table-striped table-bordered table-hover customers-table-list">
<thead>
<tr class="second">
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Country</th>
<th>City</th>
<th>Address</th>
<th>Email</th>
<th> </th>
</tr>
<tr>
<th style="width: 11%;">First Name</th>
<th style="width: 11%;">Last Name</th>
<th style="width: 11%;">Phone</th>
<th style="width: 11%;">Country</th>
<th style="width: 11%;">City</th>
<th style="width: 11%;">Address</th>
<th style="width: 11%;">Email</th>
<th class="no-sort" style="width: 13%;">Actions</th>
</tr>
</thead>
</table>
I using libraries:
Laravel
http://datatables.yajrabox.com/
JS
http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js
http://jquery-datatables-column-filter.googlecode.com/svn/trunk/media/js/jquery.dataTables.columnFilter.js
I think its a bug of these versions, because with older datatable version is good.

Related

Get MySQL Query using Ajax then Inserting Result to Data Table on button click

I want to ask how can I insert my sql query to the html datatable table body.
This is my present code:
AJAX Query for loading datatable after button click:
$(document).on('click','#filtersearch',function(e){
e.preventDefault();
$.ajax({
url:"index.php",
method:"POST",
data:{
formula:"filtersearch"
},
dataType:"json",
beforeSend:()=>{
$('.load_spinner').removeClass('d-none');
},
success:function(res){
$('.load_spinner').addClass('d-none');
select_d = res;
console.log(res);
var str ="";
if (!$.isEmptyObject(select_d)) {
select_d.forEach((x)=>{
str += `<tr>
<td>${x.assetid}</td>
<td>${x.assetcode}</td>
<td>${x.assetserial}</td>
<td>${x.assetname}</td>
<td>${x.assettype}</td>
<td>${x.assetcat}</td>
<td>${x.dpurchased}</td>
<td>${x.price}</td>
<td>${x.dperiod}</td>
<td>${x.finprice}</td>
<td>${x.status}</td>
<td>${x.assetage}</td>
<td>${x.location}</td>
</tr>`;
})
}
data_table("#table_index","#tbody_index",str);
}
})
})
Javascript for Datatable Content transfer from AJAX:
function data_table(table_name,tbody_name,data_tbody) {
$(table_name).DataTable().destroy();
$(tbody_name).empty().html(data_tbody);
$(table_name).DataTable();
};
Datatable HTML cointainer that will get the ajax query:
<table class="table table-bordered" id="table_index" width="100%" cellspacing="0">
<thead>
<tr>
<th>No.</th>
<th>Asset Code</th>
<th>Asset Serial</th>
<th>Asset Name</th>
<th>Category</th>
<th>Type</th>
<th>Date Purchased</th>
<th>Initial Price (PHP)</th>
<th>Depreciation Period</th>
<th>Final Price (PHP)</th>
<th>Status</th>
<th>Classification</th>
<th>Location</th>
</tr>
</thead>
<tbody id="tbody_index">
</tbody>
</table>
PHP code for database query:
<?php
include 'include/dbconfig.php';
$sql = 'SELECT * FROM tbl_assets';
$result = mysqli_query($conn, $sql);
$formula ='';
if (isset($_POST['formula'])) {
$formula = $_POST['formula'];
}
switch ($formula) {
case 'filtersearch':
$result = filtersearch();
$supData = array();
while ($row = $result->fetch_assoc()) {
$supData[] = $row;
}
echo json_encode($supData);
break;
default:
break;
}
function filtersearch()
{
include 'include/dbconfig.php';
$query = mysqli_query($conn,"SELECT * FROM tbl_assets");
return $query;
}
?>
I just want to ask what is wrong with my code since the script doesn't show the values of Tbody as intended. Thanks.
I found a solution after manipulating the pages instead.
Instead of coding all of them in one page, I tried creating another page (switchcase.php) that contains the PHP files and it worked as intended.
Just a hunch, but I think ajax doesn't accept urls of the same page. I don't know if thats how it works but yeah, I changed the url to switchcase.php and it worked.
if you using datatable with ajax and php try this way
<script>
$(function(){
$('#table_index').dataTable( {
'lengthMenu': [[10, 25, 50, 100, 500], [10, 25, 50, 100, 500]],
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'order': [[ 1, "desc" ]],
'ajax': {
'url': 'index.php'
},
"columns": [
{ "data": "id" },
{ "data": "asset_code" },
{ "data": "asset_serial" ,'bSortable': false},
{ "data": "asset_name" ,'bSortable': false},
{ "data": "category_id" ,'bSortable': false},
{ "data": "type", 'bSortable': false},
{ "data": "date_purchased"},
{ "data": "initial_price" },
{ "data": "depreciation_period" },
{ "data": "final_price" },
{ "data": "status" ,'bSortable': false},
{ "data": "classification" },
{ "data": "location" }
]
});
$.fn.dataTable.ext.errMode = 'none';
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover table-nomargin table-condensed" id="table_index">
<thead>
<tr>
<th>No.</th>
<th>Asset Code</th>
<th>Asset Serial</th>
<th>Asset Name</th>
<th>Category</th>
<th>Type</th>
<th>Date Purchased</th>
<th>Initial Price (PHP)</th>
<th>Depreciation Period</th>
<th>Final Price (PHP)</th>
<th>Status</th>
<th>Classification</th>
<th>Location</th>
</tr>
</thead>
<tbody></tbody>
</table>

Hide/show column in data table

I have data table which have 10 column(th). 5th column header and value should show only if $userRole === 'Admin'.
I am able to do this while creating table header by giving condition in php(if ($userRole === 'Admin')),so if $userRole is Admin then only this column header will display otherwise it won't display.
Same thing i need in column filed also in jquery(in data table),if $userRole === 'Admin' then only { "data": "course_exam_status" } should display.how to handle this in data table not sure.
conclusion:5th column (Pending Score) with column value({ "data": "course_exam_status" }) should display only if $userRole === 'Admin',for other role this 5th header and role there should not be display .
$(document).ready(function() {
table = $('#data_listing').DataTable({
serverSide: true,
paging: true,
searching: false,
processing: false,
bLengthChange: false,
aaSorting: [],
aoColumnDefs: [{
'bSortable': false,
'aTargets': [-1,0,2, 4]
}],
ajax: {
url: "/training/course",
type: 'POST',
dataType: 'json',
dataSrc: function(result) {
if (result.data != "") {
for (var i = 0; i < result.data.length; i++) {
result.data[i].subdomain = creating_action(result.data[i]);
if (result.data[i].roleName === "Admin") {
result.data[i].course_name = creating_checkbox(result.data[i]);
}
}
}
return result.data;
},
},
columns: [{
"data": "course_name"
},
{
"data": "instructorName"
},
{
"data": "organization_name"
},
{
"data": "timezone"
},
{
"data": "course_exam_status"
},
{
"data": "startdate"
},
{
"data": "status"
},
{
"data": "isimported"
},
{
"data": "studentcount"
},
{
"data": "subdomain"
}
]
});
<table id="data_listing" class="table table-striped table-bordered table-hover">
<thead class="theader">
<tr>
<th scope="col">Name</th>
<th scope="col">class Name</th>
<th scope="col">Training Center</th>
<th scope="col">Time Zone</th>
<?php if ($userRole === 'Admin') { ?>
<th scope="col">Pending Score</th>
<?php } ?>
<th scope="col">Start Date & Time</th>
<th scope="col">Status</th>
<th scope="col"> ype</th>
<th scope="col">Count</th>
<th scope="col">Action</th>
</tr>
</thead>
</table>

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();
}

Showing 0 to 0 of 0 entries in DataTable

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'}
]
}
} );

datatable Error : Request for unknown parameter datatable version 1.10.12

JS:
[
{
"id":6,
"firstName":"Paul",
"lastName":"Allen",
"address":"25 1845 Owagner Lane Seattle Washington 98133",
"shift":"Afternoon",
"salary":350000,
"imageUrl":"paul_allen.jpg"
},
{
"id":7,
"firstName":"Mark",
"lastName":"Doethy",
"address":"DATA: SELECT ALL\r\n8267 Cozy Stead, Yellepit, Nunavut, X6D-9S8, CA,",
"shift":"Afternoon",
"salary":2000000,
"imageUrl":"mark_young.jpg"
},
{
"id":9,
"firstName":"Mary Alice ",
"lastName":"Young",
"address":"Wisteria Lane",
"shift":"Morning",
"salary":4500000,
"imageUrl":"MaryAlice5.jpg"
}
]
$('#drivers').DataTable({
ajax: {
url: '/api/drivers/getlist/',
dataSrc: ""
},
paging: false,
colums: [
{
data: 'id'
}
]
});
HTML:
<table class="table-condensed" id="drivers">
<thead>
<tr>
<th>Driver Id</th>
</tr>
</thead>
<tbody></tbody>
</table>

Categories