How to transform "aLengthMenu" values of dataTables into a PHP variable? - javascript

I use a dataTables table in my site with following configurations:
$('#search-table').dataTable({
"dom": "<'box-content'<'col-md-4'l><'col-md-8 text-right'f><'clearfix'>>rt<'box-content'<'col-md-6'i><'col-md-6 text-right'p><'clearfix'>>",
"aaSorting": [[ 6, "desc" ]],
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 7, 8 ] }
],
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"iDisplayLength": 50,
"pagingType": "full_numbers",
"oLanguage": {
"sSearch": 'Filter within results: ',
"sLengthMenu": '_MENU_'
}
});
I would like to know how I could get the value of "aLengthMenu" that is selected at the moment and save it as a PHP variable.
By default the first 50 lines of the table will be displayed as we can see at "iDisplayLength". Then we should have the possibility to get this number as a variable.
Then when the user changes the view to 10 (or 25, or 100, etc) the variable changes to the correspondent number.
Many thanks in advance!

I think what you are looking for is the page.len() API call that will allow you at anytime to see the page length. http://datatables.net/reference/api/page.len()
I believe, but am not certain, that the page event is fired when the page length is changed. http://datatables.net/reference/event/page
You can write a method that listens for the page event and then finds out how many records are shown, then send that data off via AJAX to the server to be stored, or handled.
Simple example:
var table = $('#data-table').DataTable();
$('#data-table').on( 'page.dt', function(){
var len = table.page.len();
alert(len);
//Sample Post
//$.post('server.php',{len:len},function(){...});
});
EDIT
I feel I should mention that the dataTables version you are using is probably not current based on the option names you included. The options changed to a more readable format fairly recently, but I believe the naming convention is still technically supported for the current version. I would update the options though to the new names in case future releases of dataTables does not support the backwards compatability.

Related

Pagination is not searching for records and not sorting my columns

I'm using the jQuery pagination plugin but I'm not able to get my data to be searched or sorted by columns.
I've searched for the documentation and also watched some videos explaining how to perform this procedure, but without success.
Right now my code looks like this:
dtAjax = $('#' + pTabela).DataTable(
{
"order": [[1, 'desc']],
responsive: true,
pageLenght: 50,
searching: true,
processing: true,
serverSide: false,
deferLoading: pTotalRegistros
}
My server Side necessarily needs to be "true", otherwise the pagination will not work properly.
However, when I leave the serverSide as "true", the functionality of searching and sorting the columns is not working, only when the serverSide is set to "false".
I have no idea how to solve this anymore, in case someone can save me..

fnPageChange is not a function

I am getting the subject error when using the following:
$("#example1").DataTable().fnPageChange(localStorage.getItem('page'),true);
From what I understand, it saves the last page of the datatable that the user clicked on. If the user has clicked on the 3rd page of the datatable, navigates to another page and then goes back to the datatable, it will still be on the 3rd page of the datatable.
And it works. The last page of the datatable is saved.
The only problem is, even though the above works, I am getting the following error in the console:
Uncaught TypeError: $(...).DataTable(...).fnPageChange is not a function
I am not sure why.
Here are some other datatable setting I have:
"iDisplayLength": 50,
"order": [[ 1, "desc" ]],
"paging": true,
"scrollY": 300,
"scrollX": true,
"bDestroy": true,
"stateSave": true,
"sPaginationType":"full_numbers",
"autoWidth": false,
"deferRender": true,
"dom": 'Bfrtip',
Why am I getting the above console error and how can I fix it?
Your use of the "stateSave": true option is what is allowing a user to return to page 3 of the DataTable, after leaving the web page entirely, and then returning.
It also saves filters and sorting selections.
If you want to do something manually, which is not handled for you by "stateSave": true, then you can use the DataTables page change event. The documentation gives an example:
$('#example').on( 'page.dt', function () {
var info = table.page.info();
$('#pageInfo').html( 'Showing page: '+info.page+' of '+info.pages );
} );
Otherwise, you can delete that line which is throwing the error - and state saving should not be affected.
Regarding fnPageChange - this is an old plug-in which has been removed from DataTables - you can see a note about this here.
DataTable começa com minúsculo é um camel case.
$("#example1").DataTable().fnPageChange(localStorage.getItem('page'),true);
change to
$("#example1").dataTable().fnPageChange(localStorage.getItem('page'),true);

Disable server-side processing for sort

I'm using of DataTables for show information in a table and I've enabled server-side load (I need that just for load data and pagination) and I don't need to search or sort by server side and I need default search and sorting (jQuery) for my table.
How can I do that ?
var table2 = $('#datatable-buttons2').DataTable({
"serverSide": true,
"processing": true,
"asSorting": ['desc', 'asc'],
"ajax": {
'type': 'POST',
'url': 'test.php?nowsearch=1',
'data': {
inputaz: $("#inputaz").val(),
inputta: $("#inputta").val(),
inputkey: $("#inputkey").val()
}
},
"columns": [{
"data": "group_name"
}, {
"data": "sender"
}, {
"data": "date"
}],
});
Maybe you can do this, customizing data retrieved in Javascript, but this is not useful.
If you sort your items in clientside with serverSide: true, it will be sorted the current retrieved data only, not based in all dataset in your database (if you actually limit results, if you don't, then use directly serverSide: false witch will retrieve all records).
For example, if you have 1000 records, you only get the data of first 10 of then only, not all (10/25/50/100). If you sort locally by age, it will sorted the retrieved 10. Then, if you go to the next page, you will notice the 2nd page is not sequential from the 1st page.
That's why you must to code your sorting/search in your back-end language when you use serverSide: true: in there you will sort first and then you return 10 records sorted.
That's the idea for this option.
Anyway... You can have pagination for client-side (serverSide: false) too by using paging option. But you need to be aware about performance.
In short, if you will handle many records, you should keep using server-side and code the sorting/search/pagination/etc from your back-end an return corresponding data. Is not so hard. You can play with parameters sent to achieve this.

DataTables - CSV Only Exports Current Rows

I have the following code
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/functions/ajax.asp",
"ordering": false,
"bFilter": false,
"dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
} );
} );
</script>
I have around hundreds of rows but when I select the an option such as CSV, it only exports what is on the screen.
Any ideas?
Thanks
The problem here is that you're using server-side processing, so the client-side dataTables plugin only has access to the data on the screen to export! You'll have to make something custom to get this data from the server.
Check out this post for a quick example: Server side excel export with DataTable
That is expected behavior for the export buttons in DataTables. They always simply export the data that is currently displayed on the screen. If you want to allow the user to export all data (and don't want to write a custom export function - if you do, see #Adam's answer), consider adding a lengthMenu option to your DataTable. This will allow users to change the number of records displayed per page, which can in turn let them show/export all records. The syntax for the lengthMenu parameter is as follows.
"lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ]
The first array shows the number of records to display for each option (in this case, 10, 25, 50, and all (-1 is all)), and the second array is what should be displayed in the user's dropdown menu.
See this stack overflow question for more detail on the topic.

jqGrid: Sorting local data clears grid

I've found similar but not identical questions on here; none of their posted answers solve this.
I have local data loaded using addJSONData. When you click a column header to sort, the grid is wiped. There are no errors in the web console/firebug. Data added by later calls to addJSONData is sorted by the selected column, at least.
My config:
jQuery('#attributes').jqGrid({
sortable:true,
datatype:"local",
colNames: cols,
colModel: colmods,
cmTemplate: {width:155, align:"left"},
multiselct: false,
shrinkToFit:false,
caption: "Node Attributes",
scroll: true,
footerrow: true,
userDataOnFooter: true,
rowNum: -1
});
My only idea is to save the data onSortCol and reload it in loadComplete. I don't much like that though. I've tried various combinations of rowNum: 9007199254740992, loadonce: true and others.
I've tried jqGrid versions 4.2.0 and 4.4.0 (in which rowNum: -1 is supported again).
Edit: The line that clears the data is the emptyRows bit in the sortData function:
if(ts.p.scroll) {
var sscroll = ts.grid.bDiv.scrollLeft;
emptyRows.call(ts, true, false);
ts.grid.hDiv.scrollLeft = sscroll;
}
Seems like the data should be saved before this happens, but I'm not familiar with this code to know where the data actually lives.
I'm newcomer to jqGRid (I only started to use it 3 days ago...) but, if you are using local, don't you also have to specify loadonce:true for sorting and paging to work?
I had a similar issue. I stumbled onto a fix though. After setting loadonce: true, if you hit the refresh button in the pager and then try to sort, it works fine.
So I force a click on the refresh button by doing something like: $(".ui-icon-refresh").trigger('click');
I ran this on the onClose event because that suited my requirements. You can check out my entire explanation on this issue here: Make 'Search' remote and everything else (sorting, pagination, etc) local in jqGrid

Categories