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
}
}
} );
} );
Related
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();
};
Here's the case.
I am using ajax call in datatable js to bind json data in my table.
Right now I am using directly json file for databinding.
Now I want to access the data from my db for which I have written a
method inside my controller which returns json value.
But I am not able to call this method like I was calling my json file
in ajax. Kindly suggest the solution.
Below are the code sample
var table = $('#example').DataTable({
"ajax": "/content/data/dataList.json", //here I want the url of my method.
"bDestroy": true,
"iDisplayLength": 15,
"columns": [
{
"class": 'details-control',
"orderable": false,
//"data": null,
"defaultContent": ''
},
{ "data": "name" },
],
"order": [[1, 'asc']],
"fnDrawCallback": function (oSettings) {
runAllCharts();
}
});
And my method id :
//Controller Name AppDetail
public string getData(string ddlid)
{
DataTable ddl = new DataTable();
string query = string.Empty;
if (ddlid == "O1")
{
query = "SELECT for O1";
}
else if (ddlid == "O2")
{
query = "SELECT for O2";
}
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter(query, con);
da.Fill(ddl);
con.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(ddl);
}
And here is the json data sample
{
"data": [
{
"name": "Aladdin"
}
]
}
Kindly Help.
if you are not using server side processing method get all data first using ajax method and use that data on data table. look at the code below... it might help you for getting some idea.
$.ajax({
url: 'api/AppDetail/getData',
method: 'get',
data :{ddlid:'01'}, // this is input parameter for your function
dataType: 'json',
contentType: 'text/json',
success: function(res){
var table=$('#example').dataTable({
data: res,
columns:[
{'data':'name'}
],
bDestroy : true,
iDisplayLength : 15,
});
}
});
If your controller works you can call it before DataTables and insert the data via the data (https://datatables.net/reference/option/data) source of DataTables
On the Controller if u are getting Data which u want, then u can return this Data to a partial view.
Note that the partial view is nothing a html table which u bulild upon Razor syntax or anything.
Then make ajax call to return this partial view, On success u can apply data table plugin.
<div id=MyTable></div>
$.ajax({
type: 'GET',
url: ControllerName/ActionName=partialView Which makes table.
success: function (data) {
debugger;
$('#MyTable').html(data); //Puting result of ajax call to the div which containg Id,
$('#PartilView_Table').DataTable({ // Applying DataTable Plugin table inside partialView
"bProcessing": true,
"bDeferRender": true,
"scrollX": true,
"stateSave": true,
"bAutoWidth": true,
"bSort": false,
"columnDefs": [
{
}
]
});
},
});
Hope this will help you..
I know that DataTables have the ajax.url() method for updating the data source URL, but I would like to know if there is a way I can change the function that is used to prepare the data to be POSTed on Ajax request. In the example below I would like to replace it with dataFunc.
The initialization part works fine.
function updateDataTable(dataFunc) {
// If DataTable initialised then update to correct function
if ($.fn.DataTable.isDataTable("#companyTable")) {
var companyTable = new $.fn.dataTable.Api("#companyTable");
companyTable.settings().ajax.data = dataFunc;
companyTable.ajax.reload();
} else {
$("#companyTable").DataTable({
bFilter: false,
processing: true,
serverSide: true,
ajax: {
url: "/api/GetCompanyRows",
type: "POST",
data: dataFunc
},
....
ajax can take a function where you can do all sorts of things, not the least of which is using localstorage. Check the documentation.
You can use ajax.data option to define a function that can be used to manipulate the data before it's sent to the server.
$('#companyTable').DataTable({
searching: false,
processing: true,
serverSide: true,
ajax: {
url: "/api/GetCompanyRows",
type: "POST",
data: function ( d ){
d.extra_search = $('#extra').val();
}
}
});
I found an alternative to Pro Hands solution, which allowed me to update the settings directly.
companyTable.settings()[0].ajax.data = dataFunc;
companyTable.ajax.reload();
I have a json rpc server that serves and rerurns json in the mode given including id results and jsonrpc keys ofa json string
{
jsonrpc: "2.0"
id: "1"
result: "{"iTotalDisplayRecords":"2","iTotalRecords":"2","aaData": [["1","Kenya","Nairobi","0","34"],["2","USA","New York","70","38"]],"sEcho":0}"
}
now the problem comes in after the response comes in the web browser and datatables just displays loding data from server forever
i have tried tried adding
..."sAjaxDataProp":"",...
but that leads to a no matching rows found. I have used the same coe in the Rpc server as a cgi script and found that i get the desired output and the tables populate well. The json response from the script is as
{"iTotalDisplayRecords":"2","iTotalRecords":"2","aaData":[["1","Kenya","Nairobi","0","34"],["2","USA","New York","70","38"]],"sEcho":1}
I would like a way to tell datatables to only choose the result part of the jsonrpc request in order to display the returned data as expected.
here is the sending datapart in my javascript
oTable=$('#ip_data').dataTable( {
"bProcessing": true,
"bServerSide": true,
"bPaginate": true,
"bScrollCollpase": true,
"sScrollY": "200px",
"sAjaxSource": "/url",
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
aoData.push({"name":"method","value":"datatables"});
aoData.push({"name":"id","value":"1"});
oSettings.jqXHR = $.ajax({
"dataType":"json",
"type":"GET",
"url":sSource,
"data":aoData,
"success":fnCallback
});//END OF AJAX
}//END OF FNSERVERDATA
});//END OF DATATABLE
Firstly, use datatables 1.10 (and update your syntax!) https://datatables.net/upgrade/1.10-convert
Secondly, read this https://datatables.net/manual/server-side
then read this https://datatables.net/reference/option/ajax
Your solution may end up looking something like
var oTable = $('#ip_data').DataTable( {
"serverSide": true,
"ajax": {
"url": "/url",
"data": {
"method": "datatables",
"id": "1",
}
},
});
I have a javascript function fetchGroups() that builds a paged data table using the datatable plugin. The request being passed in is a GET request. I need to pass a fetchMemberGroups object along with the request. I tried sending the request with the request body. But it doesn't seem to work and keeps throwing a 500-Internal Server Error. I also don't believe I can pass a request body with a GET. I then tried to pass the fetchMemberGroupsobject along with the URL by appending a #PathParam annotation on the service method. Could someone tell me how do I pass this object to the service without changing the type of the service to POST or PUT.
function fetchGroups() {
var fetchMemberGroups = new Object();
fetchMemberGroups.sEcho = 0;
$("#displayGroupsTable").dataTable({
"bServerSide": true,
"sAjaxSource":"api/groupService/groups",
"bProcessing": true,
"bJQueryUI": true,
"bRetrieve": true,
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
fetchMemberGroups.iDisplayStart=oSettings._iDisplayStart;
fetchMemberGroups.iDisplayLength=oSettings._iDisplayLength;
fetchMemberGroups.sEcho=fetchMemberGroups.sEcho+1;
oSettings.jqXHR=$.ajax( {
"contentType" : 'application/json',
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": JSON.stringify(fetchMemberGroups),
"success": fnCallback
});},
"aoColumns": [
{ "mData": "groupName" },
{ "mData": "numberOfMembers"},
{ "mData": "distinguishedName"}
]
});
}
The server side code:
#GET
#Path("groups")
#Produces({ MediaType.APPLICATION_JSON })
#Consumes({MediaType.APPLICATION_JSON})
public Response getGroups(#Context HttpServletRequest request, PagingObject fetchGroupsObject) {
}
EDIT:
you should not be using the oTable api to set your parameters to send to the server...because oSettings doesnt exist yet, oTable hasnt been created so there's no oSettings
you should not have to specify sEcho, iDisplayStart, iDisplayLength those are automatically created in a server side implementation by the framework
what you do need to do is evaluate them in your query to get your result limit, ect
if you could i would suggest trying the following, and see if it returns anything in the network inspector of firebug/chrome tools
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
fnCallback(json);
});
Previous
Im pretty sure your fnServerData is off, or at least its unlike anything ive seen
Typically i do something similar to this, where lastname is an additional parameter, and as getJSON you know its a get:
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( { "name" : "LastName", "value" : "$('#LastName').val()" } );
$.getJSON( sSource, aoData, function (json) {
fnCallback(json);
});
The 500 error also sems like the url doesnt exist, have you tried opening the url on its own rather than from ajax?