jQuery Datatable serverside reload with new post data - javascript

I have common function for all the server-side data-tables which accepts the table object, url and the post data. The post data consists of the values from the select boxes that are in the filter area.
UTIL.serverDatatable = function (table, api, data) {
var token = "Bearer " + JSON.parse(UTIL.getItemLocalStorage('token'));
return table.DataTable({
"processing": true,
"serverSide": true,
"paging": true,
"ajax": {
url: api,
type: "post",
beforeSend: function (request) {
request.setRequestHeader("Authorization", token);
},
"data": data
}
});
};
And another function to reload the datatable
UTIL.datatableReload = function(table) {
table.ajax.reload();
};
This worked fine before these functions were made common. The post data was changing when the filters changes and the reload function was called after that. But now when the data is changed, the post is not getting updated. Is there any solution for this? How to post the changed data via the ajax call?

Change the code as below
UTIL.serverDatatable = function (table, api, callback) {
var token = "Bearer " + JSON.parse(UTIL.getItemLocalStorage('token'));
return table.DataTable({
"processing": true,
"serverSide": true,
"paging": true,
"ajax": {
url: api,
type: "post",
beforeSend: function (request) {
request.setRequestHeader("Authorization", token);
},
"data": callback
}
});
};
Then call the util function as below
UTIL.serverDatatable(tablename, apiname, function(data){
data.key= $('#input1').val();
});
And then call the function as
UTIL.datatableReload = function(table) {
table.ajax.reload();
};

Related

How to send manual payload in jQuery Datatable?

I was working on jQuery data table without server-side caching and pagination earlier, but now I am getting API that is performing server-side pagination searching and sorting.
I have some idea about server-side functionality provided by data table but my question is how can
I pass my own parameters to ajax request, I have noticed that jQuery Datatable sends a payload that contains many things but I need to send some extra information as well to the backend.
My Code-
$('#dataTable').ready(function () {
$('#datatable').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
"url": "API/GetDetails",
"dataType": 'json',
"type": "GET",
"beforeSend": function(xhr){
xhr.setRequestHeader("Authorization",
"Bearer Token");
}
}
});
})
Is there any way to change the payload values sent to the backend while making Api request?
If yes how and where I should need to edit the code.
You can send custom http variables as per their documentation
https://datatables.net/examples/server_side/custom_vars.html
ex:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/server_processing.php",
"data": function ( d ) {
d.myKey = "myValue";
// d.custom = $('#myInput').val();
// etc
}
}
} );
} );

jQuery datatable generic ajax call

I am using jQuery datatables with the following code:
$table.DataTable({
lengthMenu: [10, 25, 50, 100],
processing: true,
paging: true,
ajax: {
type: "GET",
url: '',
data: function(d) {
},
dataSrc: function(json) {
//some logic
return json.items;
},
error: function(jqXHR) {
}
},
"columns": [//my columns]
});
What I want is to make the ajax request generic like below:
$table.DataTable({
lengthMenu: [10, 25, 50, 100],
processing: true,
paging: true,
ajax: ajaxForDataTable(url, methodType, function (d) { }, dataSrcCallback),
"columns": [//my columns]
});
function ajaxForDataTable(url, methodType, dataCallback, dataSrcCallback) {
$.ajax({
type: methodType,
url: baseUrl + url,
data: dataCallback,
dataSrc: dataSrcCallback,
error: function (jqXHR) {}
});
}
function dataSrcCallback() {
}
The above code is working fine and getting response from the server but the dataSrcCallback never called (where I am manipulating data) so the datatable never populates with the data (empty). As I am using this table on multiple pages, if I change any logic I have to do it on all the pages. Can anybody tell me what I am doing wrong over here so I can rectify it and make it works for me?
Take a look at the docs: https://datatables.net/reference/option/ajax .
You're suppose to pass a function to the ajax parameter and call the callback method with the data you want to pass to the datatable.
$('#example').dataTable( {
"ajax": function (data, callback, settings) {
callback(
JSON.parse( localStorage.getItem('dataTablesData') )
);
}
} );

I failed to refresh data in yajra/laravel-datatables-oracle with draw method

In laravel 6 app I use "yajra/laravel-datatables-oracle": "^9.4" and I need selecting 1 row and running ajax request on server to delete this row
I try to refresh table with draw() method and it does not work.
In my blade file :
#push('scripts')
var oTable;
$(document).ready(function () {
oTable = $('#my_tasks_data').DataTable({
processing: true,
serverSide: false,
info: false,
order: [],
});
$('div.dataTables_length select').select2({
theme: "bootstrap"
});
...
function taskComplete(rowId) {
$.ajax({
url: 'tasks/' + rowId + '/complete',
type: "post",
dataType: 'json',
data: {'_token': '{{csrf_token()}}'},
success: function (data) {
console.log('taskComplete success data::')
console.log(data)
console.log('oTable::')
console.log(oTable)
oTable.draw(); // THat does not work
alert( 'AFTER::' )
},
error: function (xhr) {
console.error(xhr)
}
});
}
I check oTable var and see : https://prnt.sc/ujyp14 It looks like valid Table object
Why it does not work and how it can be fixed?
Thanks!
I found decision with setting serverSide property to true
oTable = $('#my_tasks_data').DataTable({
processing: true,
serverSide: true,
and after that method oTable.draw() works ok

Kendo UI, datagrid inserted row produces request multiple times

i have problem with Kendo data grid component.
I'm trying to add new row into grid and create remote request to API via create event.
Problem is that if i try to add new row after first request Kendo make 2 requests instead of the one.
I tried to find some solution for this using transport create and options.success method but without luck.
http://docs.telerik.com/kendo-ui/api/framework/datasource#configuration-transport.create
Could somebody tell to me what i'm doing wrong?
Thanks for any help.
Here is the code of the server response for create:
+ Response 200 (application/json)
{
"status": "OK",
"result":[
{
"id":22,
"username":"blahblah",
"name":"Thomas",
"surname":"Man",
"email":"to.mas.marny#gmail.com",
"created":"1399986964",
"role":"USER"
}
]
}
Here is the code of the method:
$scope.initGrid = function () {
// get access token from localstorage
var token = localStorage
.getItem($rootScope.lsTokenNameSpace);
// set pagination data
var paginationData = {
"token": token,
"data": {
"page": 1,
"items_per_page": 20
}
};
var dataPacket;
dataPacket = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: $rootScope.apiBaseUrl + "user/list",
dataType: "json",
type: "POST",
data: JSON
.stringify(paginationData),
success: function (
response) {
console
.log("List of users succesfully obtained");
console
.log(response.result);
// pass response to
// model
options
.success(response);
// $notification.enableHtml5Mode();
},
error: function (error) {
console
.log("user list request error");
console.log(error);
$notification
.error(
"User list cannot be loaded",
"Please try again in a minute.");
}
});
},
update: function (options) {
console.log("Update");
options
.success("{\"test\":\"test\"}");
},
destroy: function (options) {
console.log("destroy");
options
.success("{\"test\":\"test\"}");
},
create: function (options) {
console.log("Create");
console.log(options.data);
$.ajax({
url: $rootScope.apiBaseUrl + "user/create",
dataType: "json",
type: "POST",
data: JSON
.stringify(options.data),
success: function (
response) {
console
.log("New user created");
console
.log(response.status);
// pass response to
// model
options
.success(response.result);
// $notification.enableHtml5Mode();
},
error: function (error) {
console.log("user list request error");
console.log(error);
$notification
.error(
"User cannot be created",
"Please try again in a minute.");
}
});
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
//batch : true,
//autoSync: true,
schema: {
data: "result",
model: {
id: "id",
fields: {
id: {
editable: false,
nullable: true
},
name: {
editable: true,
nullable: false
},
username: {
editable: true,
nullable: false
}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataPacket,
filterable: true,
pageSize: 20,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: ["id", "name", "username", {
command: ["edit", "destroy"],
title: " ",
width: "200px"
}],
editable: "inline"
});
};
If you declare id inside model then you don't have to declare id inside model fields.
Also when you point
data: "result"
for the model you have to pass
options.success(response)
inside ajax's success function, not just
options.success(response.result)
I think if null is passed to the Datasource of the kendo Grid in the html helper, the Grid will be built in “remote data mode” rather than “local data mode”
and since the read Url is not set the current browser Url will be used for the read operation.
make sure to initialize the list in the Model before using it as a Datasource.

Js variable does not update in ajax

I use jstree and want to reload it with new data but I cannot send it to new data.
var $driver = 0;
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: function () { return '{"driver":"' + $driver + '"}' },
contentType: "application/json"
}
}
});
});
$(document).on('click', '.tile', function () {
var $item = $(this);
var $driver = $item.attr('data-driver');
// alert($driver);
$('#tree_folder').jstree('refresh');
});
I got the new value when clicked, it send old default data every time. Above in alert function, it can give me the right value although json post send default one even data is written with function
function () { return '{"driver":"' + $driver + '"}' }
How can I get the new value from variable?
Remove var before $driver from .tile click function as you are created global previously,
Try this,
$(document).on('click', '.tile', function () {
var $item = $(this);
$driver = $item.attr('data-driver'); // remove var from this line
// alert($driver);
$('#tree_folder').jstree('refresh');
});
Also use cache:false in jstree like,
function getDriver() {
return '{"driver":"' + $driver+ '"}';
}
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
cache: false, // cache false
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: getDriver(), // get updated driver
contentType: "application/json"
}
}
});
});
Also take a look on change ajax options in jstree from server

Categories

Resources