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>
Related
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>
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
Individual column searching (text inputs) is not working in my rails code.
My mappings.js file :
$(document).ready(function(){
$("table[role='example_datatable']").each(function(){
var dataTableInstance = $('#mappings').DataTable({
"order": [[ 4, "desc" ]],
columnDefs: [
{ "searchable": false, "targets": 6},
{ "orderable": false, "targets": 6}
],
"bFilter": false,
dom: 'Bfrtip',
pageLength: 10,
processing: true,
serverSide: true,
ajax: $(this).data('url')
});
$('#mappings tfoot th').each(function(){
var title = $('#mappings thead th').eq($(this).index()).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" name="'+title+'" />' );
});
dataTableInstance.columns().every(function () {
alert("hi");
var datatableColumn = this;
$(this.footer()).find('input').on('keyup', function () {
alert("hi2");
datatableColumn.search(this.value).draw();
});
});
});
})
My mappings.html.erb file:
<%= content_tag :table,
role: :example_datatable,
id: 'mappings',
class: 'table reconciletable table-striped table-bordered table-hover',
data: { url: mappings_path(format: :json)} do %>
<tfoot>
<tr>
<th>Id</th>
<th>Entity</th>
<th>Item</th>
<th>Group</th>
<th>Record Created On</th>
<th>Record Created By</th>
</tr>
</tfoot>
<thead>
<tr>
<th>Id</th>
<th>Entity</th>
<th>Item</th>
<th>Group</th>
<th>Record Created On</th>
<th>Record Created By</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
<% end %>
I'm able to get the input texts for each column but once I try searching & nothing happens and it's not able to filter my datatable according to column search.
This is my code. please help me out :'(
Try this
//Apply the search
table.columns().eq( 0 ).each( function ( colIdx ) {
$( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );
} );
working Demo
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
I am newbie to DataTable. here I am trying to get the of first cell value of a row when I click the viewlink associated with the row, instead of the value I am getting [object object].
heres my code
$(document).ready(function() {
// Delete a record
$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData($(this).parents('tr')[0]);
alert(aData);
} );
// DataTables init
var oTable=$('#example').dataTable( {
"sDom": "Tfrtip",
"sAjaxSource": "php/browsers.php",
"aoColumns": [
{ "mData": "browser" },
{ "mData": "engine" },
{ "mData": "platform" },
{ "mData": "grade", "sClass": "center" },
{
"mData": null,
"sClass": "center",
"sDefaultContent": 'view / Delete'
}
]
} );
} );
HTML Table:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th width="30%">Browser</th>
<th width="20%">Rendering engine</th>
<th width="20%">Platform(s)</th>
<th width="14%">CSS grade</th>
<th width="16%">Admin</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Browser</th>
<th>Rendering engine</th>
<th>Platform(s)</th>
<th>CSS grade</th>
<th>Admin</th>
</tr>
</tfoot>
Now when I Click on the view I need to Navigate to another page with the id like
view.php?id=125
Thank you
$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData(rowIndex,0);
alert(aData);
} );
From the api docs:
fnGetData
Input parameters:
{int|node}: A TR row node, TD/TH cell node or an integer. If given as a TR node then the data source for the whole row will be returned. If given as a TD/TH cell node then iCol will be automatically calculated and the data for the cell returned. If given as an integer, then this is treated as the aoData internal data index for the row (see fnGetPosition) and the data for that row used.
{int}: Optional column index that you want the data of.
Assuming your first row is your id, would you want to include the links in your dataTable initializer like this?
$(document).ready(function () {
var oTable = $('#example').dataTable({
"aoColumnDefs": [{
"fnRender": function (oObj) {
var id = oObj.aData[0];
var links = [
'View',
'Delete'];
return links.join(' / ');
},
"sClass": "center",
"aTargets": [4]
}, {
"sClass": "center",
"aTargets": [3]
}]
});
});
see: http://jsfiddle.net/9De6w/