Why do I have not necessary pagination buttons with jQuery DataTables? - javascript

I have a problem on a DataTables using pagination with server-side request.
It looks like the number of pagination buttons is not related to my results.
I always have buttons for pages 1, 2, 3, 4, 5, no matter how many results I have.
My DataTables definition:
$('#tableau_reponses').DataTable({
"ajax": {
url: '/my_api/get_reponses_ajax',
type: 'post',
data: formData
},
"paging": true,
"searching": false,
"bProcessing": true,
"serverSide": true,
"ordering": false,
"info": false,
"pagingType": "numbers",
"pageLength": 20,
"lengthMenu": [10, 20, 50, 100],
'order': [[1, 'asc']],
'columnDefs': [
{
'targets': 0,
'orderable': false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
},
{
'targets': 1,
'render': function (data) {
return '<td class="response_state_folder"></td>';
}
}
],
});
On my test environment, I know I have 29 results. My pageLength is set to 20.
So by default, on page 1, I have 20 results. When I select page 2, I have 9 results. So far so good.
But when I select page 3, 4 or 5 (and I shouldn't be able to) I have 0 results.
Why do I have "3, 4, 5" buttons when, with 29 results, I should have only 2 pages?
Of course if I have 142 results I need 8 pages...
I think I'm missing something pretty obvious here...
Thanks for your help!
===== EDIT =====
Following #Ashu's answer, I've managed to get "recordsFiltered" and "recordsTotal" in my response (respectively "20" and "29" in my example). But now, I have only one button (for page 1) where I'm expecting two.

Your server response must return how many rows are there in the filtered response from the database, and how many rows are there in total so as the database so it can set the pagination values right.
Example response :
{
"draw": 1,
"recordsTotal": 57, // these both are important and must be updated in every response
"recordsFiltered": 20, //
"data": [
[
"Angelica",
"Ramos",
"System Architect",
"London",
"9th Oct 09",
"$2,875"
],
]
}
If you need help on server-side code, You can edit or ask a new question.
More in the documentation here

Related

JQuery DataTable Page Length Not Being Honored After Page 1

I have a JQuery data table that has a large amount of data. I set the page length, but whenever I go past the first page, it does not honor the the length anymore.
As you can see, the page length is 50 which honored on the first page, but after that, the length is no longer honored.
This is my script:
dataTable = $("#sampleTable").DataTable({
"ajax": {
"url": '....',
"contentType": "application/json",
"type": "POST",
"dataSrc": ""
},
"columns": [
{"data": "name", "title": "Name"},
{"data": "value", "title": "Value"}
],
"order": [[1, 'desc']],
"createdRow": function(tr, _, rowIndex) {
return $(tr).attr('rowindex', rowIndex)
},
"bDestroy": true,
"pageLength": 50,
"lengthMenu": [ 10, 15, 20 , 30, 50],
});
The version I am using is jquery 1.21.1 and datatables 1.10.21
Update: As requested, this is what get's called by the ajax call
#PostMapping(value = Paths.SAMPLE, consumes = { MediaType.APPLICATION_JSON }, produces = {
MediaType.APPLICATION_JSON })
#ResponseBody
public Collection<SampleData> retrieveSamples() {
return sampleDBDao.retrieveData();
}
sample.tag
<table id="sampleTable" class="table" style="width: 100%">
</table>
Is the issue because there is a large amount of data?

Pushing value in array in second ajax get request

I'm using DataTables to fill a table and need some data from a different source. So I started off with render and made a second ajax request by the ID's of what I need the name of.
Here is my code, that will explain it more clearly.
$('#table').DataTable({
"ajax": "/api/url",
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/German.json"
},
"order": [[0, "asc"]],
"pagingType": "simple",
"responsive": {details: false},
"bAutoWidth": true,
"lengthChange": true,
"scrollX": false,
"aoColumnDefs": [{}],
"columns": [
{
"data": "typ_name"
},
{
"data": "mietpreise",
render: function (data, type, row, meta) {
let tmp = [],
currentCell = $("#table").DataTable().cells({
"row": meta.row,
"column": meta.col
}).nodes(0);
data.forEach(function (item) {
$.get("/api/url2/" + item.preis_kundengruppe_id, function (row, status) {
tmp.push(row.data.kundengruppe_name);
});
});
console.log(tmp);
return $(currentCell).text(tmp);
}
},
I'm expecting to have the value of kundengruppe_name in the array like ['case1', 'case2'] but in the console I get this
[]
0: "Endkunden"
1: "Händler"
length: 2
__proto__: Array(0)
So what I want is to find under 0 and 1 and not in the array as expected. What am I doing wrong? What's going on with the array?

Datatables with Ajax

I'm new to dataTabels and I'm trying to get data from a json txt file (test1.txt). This is a part of it (only 4) but I have +5000:
[{"0":"22352442","ID":"22352442","1":"22126303","PARENT":"22126303","2":"2813340","TASK_ID":"2813340","3":"2667252","CHILD_ID":"2667252","9":"Shawne Walthall","LEAD":"Shawne Walthall","11":"RP ~217' cable- PL 8 YPSIL","DESCRIPTION":"RP ~217' cable- PL 8 YPSIL","12":"PD-SW-ANN","WORKLOCATION":"PD-SW-ANN","13":"IC","TASKTYPE":"IC","14":"HOLD","STATUS":"HOLD","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"RFW672917A11 INSTALL CABLE - 05-181","TASK_DESCRIPTION":"RFW672917A11 INSTALL CABLE - 05-181","19":"Overload","TYPE_OF_WORK":"Overload","20":"16-NOV-06","TS":"16-NOV-06","21":"24-JAN-11","TC":"24-JAN-11"},{"0":"27364695","ID":"27364695","1":"27364637","PARENT":"27364637","2":"11949147","TASK_ID":"11949147","3":"11949089","CHILD_ID":"11949089","11":"08-036 Design System Cable NF 52R Howard","DESCRIPTION":"08-036 Design System Cable NF 52R Howard","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"TC","TASKTYPE":"TC","14":"WAPPR","STATUS":"WAPPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"TEST CABLE","TASK_DESCRIPTION":"TEST CABLE"},{"0":"28728012","ID":"28728012","1":"28728001","PARENT":"28728001","2":"31575951","TASK_ID":"31575951","3":"31575940","CHILD_ID":"31575940","9":"Clifton Manus","LEAD":"Clifton Manus","11":"08-098, Design\/Construct System Cable","DESCRIPTION":"08-098, Design\/Construct System Cable","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"IC","TASKTYPE":"IC","14":"APPR","STATUS":"APPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"08-097, INSTALL CABLE","TASK_DESCRIPTION":"08-097, INSTALL CABLE","19":"Reliability","TYPE_OF_WORK":"Reliability","20":"12-AUG-08","TS":"12-AUG-08","21":"12-AUG-17","TC":"12-AUG-17"},{"0":"28728014","ID":"28728014","1":"28728001","PARENT":"28728001","2":"31575953","TASK_ID":"31575953","3":"31575940","CHILD_ID":"31575940","11":"08-098, Design\/Construct System Cable","DESCRIPTION":"08-098, Design\/Construct System Cable","12":"PD-SE-TBY","WORKLOCATION":"PD-SE-TBY","13":"TC","TASKTYPE":"TC","14":"WAPPR","STATUS":"WAPPR","15":"INFLD","C_STATUS":"INFLD","16":"Scheduled","CLASSIFICATION":"Scheduled","18":"TEST CABLE","TASK_DESCRIPTION":"TEST CABLE","19":"Reliability","TYPE_OF_WORK":"Reliability","20":"12-AUG-08","TS":"12-AUG-08","21":"12-AUG-08","TC":"12-AUG-08"}]
There is around 21 columns. How can I assign this to the columns in my dataTable?
This is my dataTable script:
var dataTables = $('#myTable').DataTable({
ajax: "test1.txt",
deferRender: true,
bPaginate: true,
select: {
style: 'multi'
},
aLengthMenu: [[100, 200, 500, -1], [100, 200, 500, "All"]],
pageLength: 100});
Make these changes in your datatable initialization.
ajax: {
url: "test1.txt",
dataSrc: ''
},
Remove columns: [ ]
You will then need to format your json text file such as this
[
{
"0" : "value of 1st column of 1st record",
"1" : "value of 2nd column of 1st record",
...
...
upto 21 column
},
{
"0" : "value of 1st column of 2nd record",
"1" : "value of 2nd column of 2nd record",
...
...
upto 21 column
}
]
Try this and see if it works.
If you want to hide column, then add this in datatable
"columnDefs": [
{
"targets": [ 0, 1 ],
"visible": false,
"searchable": false
}
]
Where 0, 1 represents you column index.
0 first column, 1 second column
Enter these index number of column which you want to hide.
New Update
In the dynamic json file case, you will need to use first approach using columns
Mention what columns you want to show in the columns key like below
$('#myTable').DataTable( {
"ajax": {
url: "test1.txt",
dataSrc: ''
},
"columns": [
{ "data": "C1" },
{ "data": "C2" }
]
});
and then your json text file will be like
[{"C1":"22352442","C2":"22126303","KEY":"NO SHOW"}, {"C1":"22352442","C2":"22126303", "KEY":"NO SHOW"}]
Your first json will work in the case now.

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");

DataTable not showing pagination buttons and records info - JQuery

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.

Categories

Resources