Hide/show column in data table - javascript

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>

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>

Load DataTables dynamically in JQuery tabs

I am planning to use JQuery Datatables in one of my project, so i decided to do a POC to ensure that everything is planned.
I build a table where i will be printing the values from my Object which will be received as a JSON during my further development. But i am getting an AJAX error for the id i was going to print the data.
I have uploaded the code on JSFiddle!
HTML
<div id="tab-customers">
<table id="customers-table" class="display general-table" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th>Gender</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
</table>
</div>
JQuery
$(".tabs").click(function() {
var source = $(this).data("source");
var tableId = $(this).data("table");
initiateTable(tableId, source);
});
function initiateTable(tableId, source) {
var table = $("#" + tableId).DataTable({
"ajax": source,
order: [],
columnDefs: [{
orderable: false,
targets: [0]
}],
"destroy": true,
"bFilter": true,
"bLengthChange": false,
"bPaginate": false
});
}
initiateTable("customers-table", "customers");
$("#dynamic-tabs").tabs();
});
Try the columns option
columns: [
{ "data": "Id" },
{ "data": "firstName" },
{ "data": "lastName" },
{ "data": "email" },
{ "data": "phone" },
{ "data": "gender" },
{ "data": "city" },
{ "data": "country" }
]
Demo

unable to display sum in footer using datatable

I have created a datatable using jQuery. The table has seven columns , among one column is for Grand Total (column 6). I have to display the sum of Grand Total (column 6) in the Grand Total (column 6) at the bottom of Grand Total (column 6).
How can I do that? I have tried some code but nothing worked.
Outout is blank column.
here is the code that I found.
below is the html code
HTML
<table class="display table table-bordered table-striped" id="dynamic-table">
<thead>
<tr>
<th>Invoice Type</th>
<th>Invoice No</th>
<th>Invoice Date</th>
<th>Customer Name</th>
<th>City </th>
<th>Grand Total</th>
<th class="hidden-phone">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th>Total:</th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
JavaScript
function load_datatable() {
var data = $('input[name=report]:Checked').val();
var date = $('#rep_date').val();
var type = $('#type_id').val();
datatable = $("#dynamic-table").dataTable({
"bAutoWidth": false,
"bFilter": true,
"bSort": true,
"bProcessing": true,
"bDestroy": true,
"bServerSide": true,
"oLanguage": {
"sLengthMenu": "_MENU_",
"sProcessing": "<img src='" + root_domain + "img/loading.gif'/> Loading ...",
"sEmptyTable": "NO DATA ADDED YET !",
},
"aLengthMenu": [
[10, 20, 30, 50],
[10, 20, 30, 50]
],
"iDisplayLength": 10,
"sAjaxSource": root_domain + 'app/invoice/',
"fnServerParams": function(aoData) {
aoData.push({
"name": "mode",
"value": "fetch"
}, {
"name": "report",
"value": data
}, {
"name": "type_id",
"value": type
}, {
"name": "date",
"value": date
});
},
"footerCallback": function(row, data, start, end, display) {
var api = this.api(),
data;
// 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 this page
pageTotal = api
.column(5, {
page: 'current'
})
.data()
.reduce(function(a, b) {
return intVal(a) + intVal(b);
}, 0);
console.log(pageTotal);
// Update footer
$(api.column(5).footer()).html('$' + pageTotal);
},
"fnDrawCallback": function(oSettings) {
$('.ttip, [data-toggle="tooltip"]').tooltip();
}
}).fnSetFilteringDelay();
//Search input style
$('.dataTables_filter input').addClass('form-control').attr('placeholder', 'Search');
$('.dataTables_length select').addClass('form-control');
}
do this example :
const Table = $('#foo').DataTable({
. . . . . .,
. . . . . .,
drawCallback: function(){
Table.columns(5, {
page: 'current'
}).every(function() {
var sum = this
.data()
.reduce(function(a, b) {
var x = parseFloat(a) || 0;
var y = parseFloat(b) || 0;
return x + y;
}, 0);
console.log(sum);
$(this.footer()).html(sum);
});
}
});
in this case the column was column number 5

aoColumns of datatables are not working

Please find attached the application picture, where the column ORDER ID is not showing, and instead of that, is showing the PLUS sign. So all the columns should shift for one to the right.
ajax
And all the time when I run the application it shows me this error message:
DataTables warning (table id = 'companies'): Added data (size 3) does not match known number of columns (4)
var oTable;
$('#companies tbody td img').live('click', function () {
var nTr = this.parentNode.parentNode;
if (this.src.match('details_close')) {
/* This row is already open - close it */
this.src = "/Content/images/details_open.png";
oTable.fnClose(nTr);
}
else {
/* Open this row */
this.src = "/Content/images/details_close.png";
var orderid = $(this).attr("rel");
$.get("Me?OrderID=" + orderid, function (detalet) {
oTable.fnOpen(nTr, detalet, 'details');
});
}
});
/* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": 'AjaxHandler',
"bJQueryUI": true,
"aoColumns":
[
{ "bSortable": false,
"bSearchable": false,
"fnRender": function (oObj)
{
return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + oObj.aData[0] + '" />';
}
},
null,
null,
null
]
});
<table id="companies" class="display">
<thead>
<tr>
<th> </th>
<th>Order ID</th>
<th>Customer ID</th>
<th>Ship Address</th>
</tr>
</thead>
<tbody></tbody>
</table>
You should specify the column number in the aoColumns definition, e.g.:
"aoColumnDefs":[
{
"mData": null,
"bSortable": false,
"bSearchable": false,
"fnRender": function (oObj) {
return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + oObj.aData[0] + '" />';
}
},
{ "mData": 0 },
{ "mData": 1 },
{ "mData": 2 },
{ "mData": 3 }
]
And the HTML markup:
<table id="companies" class="display">
<thead>
<tr>
<th></th>
<th>Order ID</th>
<th>Customer ID</th>
<th>Ship Address</th>
<th>Country</th>
</tr>
</thead>
<tbody></tbody>
</table>
Use the following structure for aoColumns:
"aoColumns": [
{
"mData": 0,
"bSortable": false,
"bSearchable": false,
"mRender": function (data, type, full){
return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + data + '" />';
}
},
{ "mData": 1 },
{ "mData": 2 },
{ "mData": 3 }
]
Use the following HTML markup:
<table id="companies" class="display">
<thead>
<tr>
<th>Order ID</th>
<th>Customer ID</th>
<th>Ship Address</th>
<th>Country</th>
</tr>
</thead>
<tbody></tbody>
</table>

How to get particular column in responsive jquery datatable for small Screen

I have implemented responsive jquery datatable in one of my project.
At the end of each row there is edit/detail link.
If i click edit/detail link:
1)Large Screen - It picks the UseID(Which is first Column in a row), so that i can edit that User.
2)Small Screen - Because of responsiveness the row will splitted as show below. It doesnot pick that User ID.
Large Screen Edit/Detail is Last row
Large Screen after clicking Edit link
Small Screen See Edit/detail link which is splitted
I am not able to get the UserID alert when i click edit link whenever the screen is small.
My Code.
<table id="myExample" class="display responsive nowrap">
<thead>
<tr>
<th>User Name</th>
<th>First Name</th>
<th>LastName</th>
<th>Street</th>
<th>City</th>
<th>Zip</th>
<th>State</th>
<th>Email</th>
<th>Edit</th>
</tr>
</thead>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>
<script src="~/Scripts/dataTables.responsive.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var table = $('#myExample').DataTable({
"ajax": {
"url": "/Admin/LoadData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Usr_Nm", "autowidth": true },
{ "data": "FirstName", "autowidth": true },
{ "data": "LastName", "autowidth": true },
{ "data": "Street", "autowidth": true },
{ "data": "City", "autowidth": true },
{ "data": "Zip", "autowidth": true },
{ "data": "Sate", "autowidth": true },
{
data: null,
defaultContent: 'Edit/Detail',
orderable: false
}
]
});
$('#myExample').on('click', 'a.Edit', function (e) {
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
$.ajax({
url: '/Admin/UserEdit',
type: "GET",
data: { 'id': UserId },
dataType: "json",
success: function (response) {
// alert('1:');
// alert(response);
if (response.isRedirect) {
// alert('1');
window.location.href = response.redirectUrl;
//window.location.href = response.redirectUrl;
}
// }
},
error: function (response) {
alert("Some error");
}
});
});
})
</script>
To get UserID:
var UserId = $(this).closest('tr.').find('td').find('.sorting_1').text();
Inspect Element in Large Screen
Inspect Element in Small Screen:
You must go through the dataTables API in order to get data for columns not present in the DOM (removed due to responsiveness).
You can get the all values for a certain row by table.row(<tr-node>).data() :
$('#myExample').on('click', 'a.Edit', function (e) {
var data = table.row($(this).closest('tr')).data()
//if it is "User Name" / first column you are after
var userId = data[0]
...
})

Categories