DataTable not showing pagination buttons and records info - JQuery - javascript

Using Datatable plugin for pagination, I can't get it to display pagination buttons and records information ("Showing X out of Y Records"). It is fetching the records correctly when I am selecting the page size from the drop down just above the table, but for some reason, it is not showing pagination buttons.
My guess is that it has to know the Total Record count of the table, and I am giving it that in the ""iTotalRecords": 10000" part, I have 1000 records in my table, but still it is of no use. What exactly am I missing here?
It is passing the start (page number) and length (page size) params correctly.
Below is my code,
$('#leadDetailTable').dataTable({
"processing": true,
"serverSide": true,
"info": true,
"stateSave": true,
"lengthMenu": [[10, 50, 100, 500], [10, 50, 100, 500]],
"iTotalRecords": 10000,
"iDisplayLength": 10,
"searching": false,
"scrollY": false,
"scrollX": false,
"ajax":{
type: 'POST',
url: '#Url.Action("SearchLeads", "ResourceManagement")',
data: args,
success: function (result) {
/* Do things with result */
},
}
});

Have you tried adding following parameters:
"bPaginate":true,
"sPaginationType":"full_numbers",
"bLengthChange": true,
"bInfo" : true

I had the same issue and it was because I returned the wrong recordsFiltered value from the server-side. Make sure that the recordsTotal value represents the number of records(rows) in the table and the recordsFiltered value represents the number of rows that should stay hidden of the total rows. DataTables uses this information to create the pagination buttons.

Add the below property
"pagingType": "full_numbers"

What is the response being returned by the ajax request? It should include the following:
{
data: <the array of row data>,
draw: <the same value the request had for its draw value>,
recordsTotal: <the total number of records>,
recordsFiltered: <the total number of records after filtering>
}
If you don't want it to say "filtered from x records", then count the records after filtering and set both recordsTotal and recordsFiltered to that value.

Related

How to controll two datatable using one lengthMenu

I have two tables in the same View/Page. I am using jquery datatable and to target both the table, I have used .display in both tables.
Question: Both the table has separate tableLength dropdown, How to target both using the top dropdown?
In Layman term, since both table has separate dropdown, both works properly for respective table. I want to use first table's dropdown and If I select 25, it should select 25 for the bottom dropdown and both the tables should show 25 records.
What I tried: I have made customized dropdown (orange box) which will call onChange event and will get the value and pass that value to Datatables "aLengthMenu" and "iDisplayLength" keys.
Below screenshot is taken from the UI I am working, can't paste the full picture. "Show 5 entries" is the LengthMenu.
`
<html>
.
.
<table class="display" id="tbl_result1">
</table>
<table class="display" id="tbl_result">
</table>
.
.
</html>
$('table.display').DataTable({
"aaSorting": [],
'aoColumnDefs': [{
'bSortable': false,
'aTargets': ['col-action']
}],
"zeroRecords": "No",
"language": {
"zeroRecords": " ",
"infoEmpty": " ",
"searchPlaceholder": "Search for an issue"
},
"aLengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]], //LeftArray:value,rightArray: UI Dropdown
"iDisplayLength": 5, // By default rows
"searching": false,
"bStateSave": true,
"bPaginate": true, // true/false to enable/disable Pagination
"bInfo": false, // true/false to enable/disable the "Showing 1 of N records" message
"ordering": false, // true/false to enable/disable table sorting
'columnDefs': [{ // For disabling sorting in a particular table columns
'targets': [0], // column index (start from 0)
'orderable': false, // set orderable false for selected columns
}],
"fnStateSave": function (oSettings, oData) {
localStorage.setItem('offersDataTables', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(localStorage.getItem('offersDataTables'));
},
"dom": '<"pull-left"f><"pull-right"l>tip'
});
`
Tried calling onChange event listner and passing the value from customized dropdown, called a function that passes the value as an argument (let say variable is newLengthVal)to the Datatables like
`
"aLengthMenu": [[newLengthVal], [newLengthVal]], //LeftArray:value,rightArray: UI Dropdown
"iDisplayLength": newLengthVal, // By default rows
`

Integrate two requests into one Javascript

$("input[type='checkbox']").on("change",function(){
if($(this).is(":checked")){
$.ajax({
url: portfolio_data_url,
type: 'POST',
data: "id="+$(this).val(),
success:function(r){
// succcess call
}
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<div><input type="checkbox" value="0" checked>All</div>
<div><input type="checkbox" value="1">AppID</div>
<div><input type="checkbox" value="2">Vendor</div>
</form>
I have several checkboxes whose values are passed using a POST request. If one checkbox is selected, the value is passed to the POST request.
But I already have code that passes POST requests:
list.js
$(function () {
var table = $("#portfolio").DataTable({
"ajax": {
"url": portfolio_data_url,
"type": "POST"
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
"processing": true,
"serverSide": true,
"deferRender": true,
"language": datatables_language,
"order": [[ $(".portfolio thead th").index($(".portfolio thead .appid")), "desc" ]],
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": "no-sort"
}
]
})
});
How can I integrate the code into the list.js for everything to go with one query.
Because now two different requests are sent which lead to incorrect output of information.
You can use .DataTable function to send checkboxes checked value in one request like below:
Try this:
$(function () {
var table = $("#portfolio").DataTable({
"ajax": {
"url": portfolio_data_url,
"type": "POST",
"data": function(d){
var ids = $('input:checkbox:checked').map(function(){
return this.value;
}).get();
d.ids = ids;
}
},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"stateSave": true,
"processing": true,
"serverSide": true,
"deferRender": true,
"language": datatables_language,
"order": [[ $(".portfolio thead th").index($(".portfolio thead .appid")), "desc" ]],
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": "no-sort"
}
]
})
});
In Datatable Using the data parameter as a function allows the additional data to send to server
Official Documentation
Note: You will get checked checkboxes value as an array, You can use .join(',') after .get() to send values as comma separated string to use directly in query
Also, when user check any checkbox then we can refresh datatable ajax to send updated checked checkboxes like below:
$("input[type='checkbox']").on("change",function(){
table.ajax.reload();
});
It looks like the ajax function youy want to re-use is of DataTable's.
It's not a good idea to use the ajax function which is used by some other plugin.
Here the Ajax call you want to Re-Use is used by the function DataTable. Instead of re-using that you can create a wrap-up function which makes ajax request.
Every-time if you want to make ajax request you can call that function with specified parameters.
Example :
function customAjax(url,data,method,success_message,fail_message){
$.ajax({
url:url,
data:data,
method:method,
success:function(response){
alert(success_message);
},
error:function(response){
alert(fail_message);
}
});
}
And call using :
customAjax("xyx.php","username=abc&password=ushfush","POST","Login Successfull","Something went wrong");

Jquery Datatable is not getting recreated

I am creating jquery Datatable dynamically. ColumnNames and Rows Values are coming from Server side using Ajax call. Now, I need this datatable to be reinitialized everytime, so I used property "bDestroy": true, on every ajax call but after first display, DOM is getting broken. Here is my code
$('#JDatadt').dataTable({
"order": [],
"dom": "Bfrtip",
"buttons": ["csv", "excel", "pdf"],
"columnDefs": [{ "className": "dt-center", "orderable": false, "width": 20 }],
"bInfo": false,
"paging": true,
"processing": true,
"bDestroy": true,
"columns": dataObject[0].columns,
"data": dataObject[0].data
});
What is getting wrong here. Please help
Datatable by default try to sort column with index 0 if not specified.
if you don't want to sort by default with any column just add
"aaSorting": [[ ]] ,
you can destroy table by using fnDestroy() function of datatable. it will surely works for you.

Sort table by a column with DataTables

I'm trying to sort a table by a particular column with DataTables, but I receive this warning:
DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
I put these scripts but maybe I'm doing something wrong:
jQuery('.sp-template-league-table table').DataTable({ paging: false, searching: false, info: false, retrieve: true });
jQuery('.sp-template-league-table table').DataTable().column('.data-tot').order('asc').draw();
You can see the table in this page: http://www.quartuleague.com/goldcup-2015-girone-gold/
under the "Fair Play" Tab, i want to sort table by "TOT"
If you want to sort the data by default you can also pass along additional parameters on the initialization instead of using .draw():
Example: Ascending sorting of the 4th column (indices start at 0)
$('#example_table').DataTable( {
"order": [[ 3, "asc" ]]
} );
In your case you need to add the column number of your data-tot column (8 or -1) like so:
jQuery('.sp-template-league-table table').DataTable({
order: [[ 8, "asc" ]],
paging: false,
searching: false,
info: false,
retrieve: true
});

Jquery Datatable not showing correct number of rows as per dropdown entries

I have ajax call which returns table. In success method I use $("#tableID").dataTable(); It although shows paging and number of rows in dropdown, but it is just displaying all rows instead of only number of rows as selected in dropdown. In other words number of rows to be shown is not working.
I tried using below in $(document).ready but it also didn't work
$("#tbAccount").dataTable({
"iDisplayLength": 10
});
My code is below:
function ShowNodeDetails(levelId, parentGroupID) {
$.ajax(
{
type: "POST",
url: "AccountsView.aspx/GetNodeDetails",
data: "{'levelID':'" + levelId + "','ParentGroupId':'" + parentGroupID + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$("#dvAccountDetails").empty();
$("#dvAccountDetails").append(msg.d);
$("#tbAccount").dataTable(
{
"iDisplayLength": 10
});
}
});
}
Am using jquery, javascript and ajax from last 5 days only. So maybe, I lack maybe debugging skills in the same.
Try giving these options:
Destroy: Will recreate the datatable if it already exists.
Searching: Can be set to True or False.
Ordering: For sorted or unsorted list.
LengthMenu: Custom pager lengths per table
$('#tbAccount').dataTable( {
destroy: true,
searching: true,
ordering: true,
lengthMenu: [5, 10, 25, 50, 75, 100 ]
});

Categories

Resources