jquery data table and sorting columns - javascript

I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}

You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference

By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC

Related

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?

Getting a data from a page to another (specifically id) on my table using column render of datatables. Codeigniter

I would like to get the data of a specific row in my datatables and display it in another page where I edit the contents of the table. I have no idea how to do that. Here is my Javascript.
<script type="text/javascript">
var table;
$(document).ready(function() {
table = $('#table').DataTable({
"responsive": true,
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('Infoserbilis/ajax_list')?>",
"type": "POST"
},
"columnDefs": [{
"targets": [13], //first column / numbering column
"orderable": false,
"data": "download_link",
"render": function(data, type, full, meta) {
return 'Edit';
}, //set not orderable
}, ],
});
});
</script>

Refresh datatable data

I am trying to refresh the data from my table, but I am not using ajax and that is why when I try to use table.ajax.reload() it is not working.
It gives me wrong json response since the way I am declaring my table is this:
var table = $('.table').DataTable( {
"data": global_data,
"scrollX": true,
"pagination": false,
"lengthChange": false,
"bPaginate": false,
"language": {
"url": "http://cdn.datatables.net/plug-ins/1.10.16/i18n/Spanish.json"
},
"order": [[ 2, "desc" ]],
});
So in another process I update the variable global_data, how to refresh the data?
Thanks
If you are using datatables you can destroy the data with the following line:
$ ('# mytable'). dataTable (). fnDestroy ();
and fill the table again with the data you want.
var table = $('.table').DataTable( {
"data": global_data,
"scrollX": true,
"pagination": false,
"lengthChange": false,
"bPaginate": false,
"language": {
"url": "http://cdn.datatables.net/plug-ins/1.10.16/i18n/Spanish.json"
},
"order": [[ 2, "desc" ]],
});

Ajax request don't start immediately

How can i stop this from autoplaying, I have a search button and I want to search first before getting the data, any approach is okay to me, whether it's AJAX side or Javascript side, please help.
Javascript
var table = $('#SARDatatable').DataTable({
"processing": true,
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-2'i><'col-sm-5'B><'col-sm-5'p>>",
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'print'
],
"ajax": {
"url": '/Home/GetAllSAR',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.sarcode = $('#txtSAR').val();
d.searchParameters.stype = $('#txtSType').val();
}
},
"columns": [
{ "data": "sarcode", "autoWidth": true },
{ "data": "stype", "autoWidth": true },
{ "data": "amount", "autoWidth": true },
{ "data": "filterno", "autoWidth": true }
]
});
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
If I understand you correctly, you would like to only initialize the table after a button has been clicked, so that the AJAX request to get the data will not be issued before clicking the button.
If this is the case, then I would suggest the following:
Have a button that inits the table:
HTML
<button id='initTable'>Init Table</button>
JavaScript
var table;
$('#initTable').on('click', function() {
table = $('#SARDatatable').DataTable({ // code to init the DataTable });
});
Have the 'reload' button
HTML
<button id='btnSearch'>Reload</button>
JavaScript
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
After you init the table, you can hide the "Init Table" button, so that there will be only one button at a time.
Hope this helps.

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Categories

Resources