dataTables sorting not working - javascript

I have a dataTable where i populating some data but i need the sorting operation enabled on that table.But my sorting is not working.This is my code i have done so far.
$('#example').dataTable( {
"processing": true,
"serverSide": true,
aaSorting: [[2, 'desc']],
"ajax": url,
"columns": [
{"data" : "code"},
{ "data": "description"},
{ "data" : "mrpString"},
{ "data":"unitDescription"},
{ "data":"moq"}
],
"columnDefs": [
{
"targets": [ 0 ],
"visible": true,
"searchable": false,
"sortable" :false
},
{
"targets": [ 1 ],
"visible": true,
"searchable": true,
"sortable" :true
},
{
"targets": [ 2 ],
"visible": true,
"searchable": false
},
{
"targets": [ 3 ],
"visible": true,
"visible": true,
"searchable": true
},
{
"targets": [ 4 ],
"visible": true,
"visible": true,
"searchable": true
}
],
"aoColumnDefs": [
{ "bSortable": true, "aTargets": [0,1,2,3,4] }
] ,
"rowCallback": function( row, data ) {
$("td:eq(0)",row).html("<a href='"+data.url+"' target='_new'>"+data.code+"<//a/> ");
//alert(data.parentCategoryId);
/* $('td:eq(6)', row).html( '<input type="checkbox" name="selectedIds" value="'+data.id+'" />' ).attr("class","checkIds");
$('td:eq(0)',row).attr('id','_'+data.id); */
}
});
});
This is my code i have done searching is also working but i want sorting enanled ,somebody please help

I know it's an old post.. but check it out..
Server side means you are doing everything server side. On the server, whatever method that fetches the data for your table, is also responsible for the paging and sorting of your table. My sorting wasn't working.. then I realized that my server-side method wasn't doing the sorting! So.. in a nutshell, I added this to the server-side method or function responsible for providing data for my table (C#):
(Note: "data" is a list of objects for my data table)
var myJsonOrder = JsonConvert.DeserializeObject<List<DataTableOrder>>(Request.Params["JsonOrder"]);
// Sorting
if (myJsonOrder != null && myJsonOrder.Count > 0)
{
var firstOrder = myJsonOrder.FirstOrDefault();
switch (firstOrder.column)
{
case 1:
data = firstOrder.dir == "asc" ? data.OrderBy(x => x.TripName).ToList() : data.OrderByDescending(x => x.TripName).ToList();
break;
case 2:
data = firstOrder.dir == "asc" ? data.OrderBy(x => x.TripStartDate).ToList() : data.OrderByDescending(x => x.TripStartDate).ToList();
break;
case 3:
data = firstOrder.dir == "asc" ? data.OrderBy(x => x.NumTravelers).ToList() : data.OrderByDescending(x => x.NumTravelers).ToList();
break;
case 4:
data = firstOrder.dir == "asc" ? data.OrderBy(x => x.NumCardsAssigned).ToList() : data.OrderByDescending(x => x.NumCardsAssigned).ToList();
break;
}
}
There is other data available in the request, such as the columns and search query:
var myJsonColumns = JsonConvert.DeserializeObject<List<DataTableColumn>>(Request.Params["JsonColumns"]);
var myJsonOrder = JsonConvert.DeserializeObject<List<DataTableOrder>>(Request.Params["JsonOrder"]);
var myJsonSearch = JsonConvert.DeserializeObject<DataTableSearch>(Request.Params["JsonSearch"]);
Edit: Sorry, learning this as I'm going.. that column / order / search data is available on the server because in my AJAX call for dataTables, I am passing the data to the server:
inactiveTravelerDataTable = $("#inactive-traveler-list-data-table").dataTable({
"processing": true,
"serverSide": true,
"jQueryUI": true,
"searching": false,
"dom": 'rtipl',
"ajax": {
"url": '/Trip/JsonInactiveTravelerList/',
"data": function(d) {
d.TripId = $('#TripId').val();
d.JsonColumns = JSON.stringify(d.columns);
d.JsonOrder = JSON.stringify(d.order);
d.JsonSearch = JSON.stringify(d.search);
},
"type": "POST"
}
//.... Continued on...
Hope this helps somebody.
Regards,

Related

DataTable change properties with Media Query

I want to change the scrollX property of my DataTable to true when switched to mobile but I don't know how to do that, I have tried using media query but it does not seem to work. Any idea?
var mobview = window.matchMedia( "(max-width: 425px)" );
$(document).ready(function() {
var table = $('#datatable').DataTable( {
"scrollX": false,
"bLengthChange": false,
"ajax": "src/json/AttendanceReport.json",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "id" },
{ "data": "FullName" },
{ "data": "DaysPresent" },
{ "data": "DaysAbsent" },
{"data":"DaysLate"}
],
"order": [[1, 'asc']]
} );
if (mobview.matches) {
table.scrollX=true;
}
$(document).ready(function() {
var mobview = window.matchMedia( "(max-width: 425px)" );
var table = $('#datatable').DataTable( {
"scrollX": !mobview.matches,
"bLengthChange": false,
"ajax": "src/json/AttendanceReport.json",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "id" },
{ "data": "FullName" },
{ "data": "DaysPresent" },
{ "data": "DaysAbsent" },
{"data":"DaysLate"}
],
"order": [[1, 'asc']]
});
EDIT
matchMedia() method returns a object that can then be used to determine if the document matches the media query string.
mediaQueryList = window.matchMedia(mediaQueryString)
Where mediaQueryString stores information on a media query.
You can invoke multiple mediaQueryString as well, Let say an example
const mediaQueryList = window.matchMedia('(min-width: Xpx), (max-height: Ypx)');
It will result in output as follows
MediaQueryList {media: "not all, not all", matches: false, onchange: null}
Description of output (MediaQueryList)
media - A DOMString representing a serialized media query.
matches - Bolean (true/False)

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?

how to add data in datatable?

I am trying to add data dynamically in datatable.I have initialized table on document.ready and created an instance of it.After that, I am trying to add data in the table using instance.
$(document).ready(function() {
//Initialize tooltips
table_sgdFile_list_linked = $('#sgdFile_list_linked').DataTable({
bSort: false,
destroy:true,
bLengthChange: false,
pageLength: 4,
columns: [{
title: "Name"
},
{
title: "Action"
}
]
});
});
I am trying to bind the data
table_sgdFile_list_linked.data(dataSet)
but it is not working.
my_list = $('#my-table-html-id').DataTable( {
"processing": true,
"serverSide": false,
"paging": true,
"bLengthChange" : true,
"bFilter": false,
"pageLength": 10,
"info": false,
"ordering": true,
"ajax": "PATH-OF-MY-API",
"columnDefs": [
{
"render": function ( data, type, row ) {
var html = data + " Modified!";
return html;
},
"orderable": false,
"targets": 1 //Last column
},
],
})
you can try this:
to add 1 row: table_sgdFile_list_linked.row.add(rowJson).draw();
to add multiple rows: table_sgdFile_list_linked.rows.add(rowsJson).draw();
following worked for me :
table_sgdFile_list_linked.clear().draw();
$('#sgdFile_list_linked').dataTable().fnAddData(trHTML);

Hide columns not working properly with server side processing in jquery datatables

I am using jquery datatables(1.10.9) with server side processing.
tab = $('#'+div).dataTable( {
"sDom": 'T<"clear">frltip',
"aaSorting": [],
"bAutoWidth" : false,
"sPaginationType": "full_numbers",
"sScrollY": "550px",
"sScrollX": "100%",
"bFilter": true,
"aoColumnDefs": [{ "bSearchable": false, "aTargets": [ 2 ] },{ "bSortable": false, "bSearchable": false, "aTargets": [ 12 ] },{ "bSortable": false, "bSearchable": false, "aTargets": [ 13 ] }],
"oTableTools": {},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": 'data/getdata',
"fnServerParams": function ( aoData ) {
},
"fnRowCallback": function( nRow, aData, iDisplayIndex ){
// Processing data like:
// $('td:eq(2)', nRow ).html( 'Test' );
}
});
// Hiding 5th column
tab.fnSetColumnVis( 5, false); //Does not work.Removes the column header but not the row data.
How do I get hide column to work properly with server side processing in jquery datatables?
I got this to work as follows:
fnDrawCallback: function() {
$('td:nth-child(3),th:nth-child(3)').hide();
}]
tab.fnSetColumnVis( 3, false) will not work because it re-fetches the data.Hence, had to do it using simple old jquery.
fnSetColumnVis() function has 3rd property (true or false) that not rebind the data. so try with fnSetColumnVis(3,false,flase) may be it can help.
You do it when you set up the datatable, using "ColumnDefs" thusly, where targets is the number of the column you want to hide:
tab = $('#'+div).dataTable( {
"columnDefs": [{ targets: 5, visible: false }],
"sDom": 'T<"clear">frltip',
"aaSorting": [],
"bAutoWidth" : false,
...
If you have 2 hidden columns, it will look like this:
"columnDefs": [{ targets: 5, visible: false }, { targets: 6, visible: false }],
Note: column numbering starts at 0.

DataTable bSortable columnDefs issue

$(document).ready(function () {
var dt = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": "api.php?t=clients",
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"columns": [{
"className": "details-control",
"data": null,
"defaultContent": " "
}, {
"data": "c_name"
}, {
"data": "c_number"
}, {
"data": "c_link"
}]
});
});
My code throw an error of SQL access violation when I included the following with
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [0] }
]
But if i remove it, everything works fine, basically I just want disable sorting for column 0
How do I achieve it.
Thanks!!
Change "aoColumnDefs" to "columnDefs"
"columnDefs": [{
'bSortable': false, 'aTargets': [0]
}]
make sure you include these script files:
http://code.jquery.com/jquery-1.11.3.min.js
https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js

Categories

Resources