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
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 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>
I have 300,000+ rows, when I test my project the Datatable is loading for about 30sec then this error occured
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
btw I am using Jquery Datatables, this is my code:
HomeController.cs:
public JsonResult GetAllRecords()
{
var records = GetRecords().ToList();
return Json(new { data = records }, JsonRequestBehavior.AllowGet);
}
Javascript:
var FilterSAR = $('#RecordsDatatable').DataTable({
"ajax": {
"url": '/Home/GetAllRecords',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "ssn_or_tin", "autoWidth": true },
{ "data": "cusid", "autoWidth": true },
{ "data": "accountNo", "autoWidth": true },
{ "data": "dateTrans", "autoWidth": true },
{ "data": "transCode", "autoWidth": true },
{ "data": "transdescription", "autoWidth": true },
{ "data": "amount", "autoWidth": true },
{ "data": "cashin", "autoWidth": true },
{ "data": "cashout", "autoWidth": true },
{ "data": "source", "autoWidth": true }
]
});
Index.chtml
<table class="table table-hover table-bordered" id="RecordsDatatable">
<thead>
<tr>
<th>SSN or TIN</th>
<th>Customer ID</th>
<th>Account Number</th>
<th>Date Transaction</th>
<th>Trans Code</th>
<th>Trans Description</th>
<th>Amount</th>
<th>Cash in</th>
<th>Cash out</th>
<th>Source</th>
</tr>
</thead>
</table>
Then i searched for solutions online and i found this code:
public JsonResult GetAllRecords()
{
var jsonResult = Json(GetRecords().ToList(), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
The error is gone but my records are still not showing, i think it has something to do with the Json code, I also found other solution like the Serialize but i can't seem to make it work with my code maybe because i am using JsonResult not ContentResult, I'm not sure.
In HomeController.cs use this
return new JsonResult() { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet, MaxJsonLength = Int32.MaxValue };
instead of
return Json(new { data = records }, JsonRequestBehavior.AllowGet);
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>
I want to try pagination using datatables.net via ajax.
I have 2 input fields which sends start date and end date and following is the table structure
<table class="table table-hover" id="example">
<thead>
<tr>
<th>Loan ID</th>
<th>Date</th>
<th>Loan Amount</th>
<th>Loan Type</th>
</tr>
</thead>
<tbody id="amount"></tbody></table>
when the button is clicked,I am calling this function
$('#recv').click(function(){
var fromDate=$('#from').val();
var toDate=$('#to').val();
var test=$.ajax({
type: "GET",
url: "/project/getDetails",
data:{"fromDate":fromDate,"toDate":toDate},
dataType:"json",async:false
}).responseText;
var result = eval('('+test+')');
$('#example').dataTable( {
"bServerSide": true,
"sAjaxSource": result,
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
When Ever I click on the button then I get error in alert box saying datatables warning id=example ajax error
Can anybody please tell me how to solve?
Let datatables take care of the ajax call:
var oTable = $('#example').dataTable( {
"bServerSide": true,
"iDeferLoading": 1,
"sAjaxSource": "/project/getDetails",
"fnServerParams": function (aoData) {
aoData.push({ "name": "fromDate", "value": $('#from').val() });
aoData.push({ "name": "toDate", "value": $('#to').val() });
},
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
$('#recv').click(function(){
oTable.fnDraw();
});
Points to note:
fnServerParams this passes your start & end date to the
getDetails function
iDeferLoading - prevent table population on page load
fnDraw() populates the datatable from your click event