Using DataTables Plugin with GET requests to pass requestbody - javascript

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?

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
}
}
} );
} );

Get data from controller in json form inside a datatable

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..

How to change Ajax request type and data

I'm using jQuery DataTables and I have a table that is loading data via an Ajax request. The Ajax source is being set at initialization.
However, I would now like to change the request type to a POST and include a data object before I force an Ajax reload.
I am doing something like this, but it doesn't work:
dt.ajax.type = 'POST';
dt.ajax.data = {<some data here>};
dt.ajax.reload();
I am only able to change the Ajax source URL, but that doesn't need to change.
You can use ajax option to define a function to call $.ajax method as shown below:
$('#example').dataTable( {
"ajax": function (data, callback, settings) {
if(some_condition){
data.param1 = "A";
data.param2 = "B";
}
$.ajax( {
"dataType": "json",
"type": (some_condition) ? "GET" : "POST",
"url": "/json.php",
"data": data,
"success": callback
});
}
});
This function will be called on initialization and every time you call ajax.reload().

Make jquery datatables to extract and use a given part of a returned json from an Rpc server

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",
}
},
});

Datatables: custom function inside of fnRowCallback

Trying to run function inside of fnRowCallback.
jQuery reports this error:
too much recursion
/js/jquery.js
Line: 4
Cannot find this neverending loop.
alert(aData.toSource()); shows array which i'm trying to loop through.
var clientId = 1234;
var reportData = $('#report-data').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "?go=report&do=process&action=get-report",
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push({ "name": "client_id", "value": clientId });
$.getJSON( sSource, aoData, function (json) {
fnCallback(json);
});
},
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
formatDates(nRow,aData);
},
});
function formatDates(nRow,aData) {
// alert(aData.toSource());
for(i=0; i!=aData.length; i++) {
if (aData[i].match(/^([0-9]{4}-[0-9]{2}-[0-9]{2})T([0-9]{2}:[0-9]{2}):[0-9]{2}\.[0-9]{3}$/gi)) {
reportData.fnUpdate('New Date Format', nRow['_DT_RowIndex'], i);
}
}
}
For each row, fnRowCallback is called, which calls fomatDates, which is calling fnUpdate, which redraws the table, calling fnRowCallback...
EDIT: Thinking about this more, forcing a redraw may cause the recursion problem all over again. Instead, replace the call to fnUpdate in your fnRowCallback to this:
$(nRow).find('td:eq(' + i + ')').text('New Date Format');
This will update the text of the i-th TD element to 'New Date Format', which is what it appears you're wanting to do.

Categories

Resources