Update ajax data programatically for jQuery datatables - javascript

I have a jQuery datatable with an ajax datasource defined like so:
var selected_ids = [];
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': {
'member_ids' : JSON.stringify(selected_ids)
},
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});
$('#available_members').on('click', '.select', function(e) {
e.preventDefault();
member_id = $(this).data('member-id');
selected_ids.push(member_id);
selected.api().ajax.reload();
});
As you can see I am updating the contents of selected_ids manually and I want to then refresh the datatable. This is working except that when the datatable reloads and does the ajax call the member_ids parameter that it passes to the server is still empty. Do I have to update the data property of the ajax call manually before reloading the table and if so how do I do that?

I fixed it I used a closure for the data attribute instead like so:
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': function ( d ) {
d.member_ids = selected_ids;
return d;
}
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});

Related

JQuery Datatable initialization

I'm getting this error while trying to supply JSON into my DataTable:
DataTables warning: table id=myTable - Requested unknown parameter 'a' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
This is what my JSON looks like:
[{
"a": "asdsaddas",
"b": "asdasda",
"c": "0000000001",
"d": "name"
}]
When user clicks button I'm generating and showing the table with an AJAX callback:
$('#find_button').click(function() {
event.preventDefault();
if (validateAll()) {
$("#myTable").DataTable({
"lengthChange": false,
"pageLength": 20,
autoWidth: false,
serverSide: true,
processing: true,
"dataSrc": "",
"ajax": function(data, callback, settings) {
var $form = $("#my_form_id");
var jsonData = getFormData($form, data.start, data.length);
var request = $.ajax({
type: "POST",
url: "api",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData),
dataType: "json"
});
request.then(function(response) {
console.log(JSON.stringify(response.data));
callback({
data: [JSON.stringify(response.data)],
recordsTotal: response.total,
recordsFiltered: response.total
})
}, failCallback);
},
columns: [{
"data": "a"
}, {
"data": "b"
}, {
"data": "c"
}, {
"data": "d"
}],
filter: false,
info: false,
ordering: false
});
$('#htmlTable').show();
}
});
I've read a lot of related questions with same bug, but still cannot make it work in my case. Maybe there is problem that DataTable is initialized before it gets response from server?

How to pass textbox value by ServerSide datatable ajax call in MVC5

I have a server side data-table.
When I make an ajax call, it does not send the given value in the text-box, it sends empty.
When I pass static data it's working fine.
This is fine:
var table = $("#tblUsers").DataTable({
"language":
{
"processing":
"<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax":
{
"url": "/Client/GetData",
"type": "POST",
"dataType": "JSON",
'data': ({ ZoneID: zoneIDs })
},
"columnDefs": [
{
"targets": [0],
"width": "5%",
"hidden": true,
}
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
//console.log(nRow);
$(nRow).find("td:eq(0)").attr("hidden", true);
return nRow;
},
"columns": [
{
"data": "ClientDetailsID"
}]
});
But when I pass zoneid from textbox value instead of static data it sends empty.
"data": { ZoneID: $("#txtSOmething").val() }
Change your data to
data: function(d){
d.myValue = $("#txtSOmething").val();
}
The on the server look for myValue in the Request. For example, asp mvc: Request.Form.Get("myValue")

Jquery datatables amount of pages

I'm trying to use jquery datatables with backend on Spring HATEOAS which returns HAL document with structure:
{
"_embedded": {...},
"_links": {...},
"page": {
"size": 10,
"totalElements": 15,
"totalPages": 2,
"number": 0
}
}
Currently my datatable settings looks like:
const table = TABLE_ELEMENT.DataTable({
processing: true,
ordering: false,
serverSide: true,
paging: true,
pagingType: 'numbers',
pageLength: 10,
lengthChange: false,
recordsTotal: 15,
searching: false,
ajax: {
type: 'GET',
url: '/api/employees',
dataSrc: data => data._embedded.employees,
},
columns: [
{data: 'name'},
{data: 'email'},
{data: 'phone'},
{data: 'birthDay'}
]
});
But the problem is that I can't properly setup number of pages I have. If I use serverSide: true my table has infinite amount of pages, if i use serverSide: false instead my table has only 1 page. How to solve this?
To switch between pages I use code:
TABLE_ELEMENT.on('page.dt', () => {
table.ajax.url('/api/employees?page=' + table.page.info().page);
});
to solve this I replaced property dataSrc, with:
dataFilter: (data) => {
let json = JSON.parse(data);
json.recordsTotal = json.page.totalElements;
json.recordsFiltered = json.page.totalElements;
json.pageLength = json.page.size;
json.data = json._embedded.employees;
return JSON.stringify(json);
}
also properties
pageLength: 10,
recordsTotal: 15
can be removed

jquery data table and sorting columns

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

How to refresh datatable list jquery?

I am using DataTable Jquery for bind list of records. I face below issue.
I am using jquery model popup for addnew and update record in MVC 4.0 Razor with no submit button only using ajax function. When I am click on "save" button and I want to update list with latest changes, but it can not. My code as below.
For Index page for list bind.
<script type="text/javascript">
$(document).ready(function () {
if (fnServerObjectToArray) {
var oTable = $('.datatable').dataTable({
"bJQueryUI": true,
"sScrollX": "",
"bSortClasses": false,
"aaSorting": [[0, 'asc']],
"bAutoWidth": true,
"bInfo": true,
"sScrollY": "100%",
"sScrollX": "100%",
"bScrollCollapse": true,
"sPaginationType": "full_numbers",
"bRetrieve": true,
"bProcessing": true,
"sAjaxSource": $('.datatable').attr('data'),
"aoColumns": [
{ sType: 'string' },
{ sType: 'string' },
{ sType: 'string' },
{ sType: 'string' },
{ bSortable: false }
],
"fnServerData": fnServerObjectToArray()
});
}
});
fnServerObjectToArray = function () {
return function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": function (json) {
var a = [];
for (var i = 0, iLen = json.aaData.length; i < iLen; i++) {
var inner = [];
inner.push(json.aaData[i].Name);
inner.push(json.aaData[i].Price);
inner.push(json.aaData[i].Phone);
inner.push(json.aaData[i].Email);
inner.push("<a title='Edit Place' class='EditDialogPlacesToStay' href='/placetostay/" + json.aaData[i].Id + "/edit'><img src='/Content/images/icons/small/grey/pencil.png' title='Edit' /></a> <a class='DeleteConfirm' href='/placetostay/" + json.aaData[i].ID + "/delete'><img src='/Content/images/icons/small/grey/trashcan.png' title='Delete' /></a>");
a.push(inner);
}
json.aaData = a;
fnCallback(json);
},
"error": function (error) {
}
});
}
}
</script>
On save button in success function I call the location.reload().
But I could not bind the latest changes of records means List is not refreshed.
Please help me for same.
Wrap the datatable initialization into a function, like initDataTable(), and add the option bDestroy to the settings :
function initDataTable() {
if (fnServerObjectToArray) {
var oTable = $('.datatable').dataTable({
"bDestroy" : true, //<-- add this option
"bJQueryUI" : true,
...
//anything as above
});
}
}
$(document).ready(function () {
initDataTable();
});
when you want to refresh / reload, like by a click on a button :
<button id="refresh">Refresh</button>
$("#refresh").click(function() {
initDataTable();
});
here is a demo -> http://jsfiddle.net/cxe5L/
To avoid the cache-issue
jQuery dataTables has hardcoded cache : true into its AJAX-calls. You have "sAjaxSource": $('.datatable').attr('data'). I assume data holds the path to an external resource, like /data/getdata.asp or similar? Add a timestamp as param to that resource, like
sAjaxSource : $('.datatable').attr('data')+'?param='+new Date().getTime()
so the sAjaxSource becomes on the form
/data/getdata.asp?param=1401278688565
This is basically the same thing jQuery is doing, when cache : false is set on a AJAX-request.
location.reload() will refresh the page content and your
$(document).ready(function () {}
is executing again instead of getting the latest changes. Check weather your database has new records or not.

Categories

Resources