Get data from controller in json form inside a datatable - javascript

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

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

how to make redraw datatables after ajax response

I have a problem here, first I create data tables after I select the user using select2, so the data is dynamic according to the selected user, then next to it there is an update data button, here serves to update the data from the API if there is the latest data, for the process the data update is no problem, but there is a problem in the data tables process where after the update process, the data tables don't want to be redrawn
$("#name").on("change",function(){
var cek_id = this.value;
$("#user_id").val(cek_id);
console.log(cek_id);
$('#getData').DataTable().clear().destroy();
var i = 1;
var VendorClient = $("#getData").DataTable({
order: [ 0, "asc" ],
processing: true,
serverSide: false,
ajax: "{{route('get-user-data')}}"+"/"+cek_id,
columns: [{
data: null,
render: function ( data, type, full, meta ) {
return meta.row+1;
} },
{
data: "fullname",
name: "fullname",
orderable:false
},
{
data: "date",
name: "date",
orderable:false
}
]
});
});
and here is the process when the data update is clicked
$("#get_data").on("click",function(){
var cek_id = $("#user_id").val();
var url = "{{route('get-update-data')}}"+"/"+cek_id,
$.ajax({
type: "get",
url: url,
dataType: "json",
success:function(data){
if(data.status=='success'){
$('#getData').data.reload();
}else{
$('#getData').data.reload();
}
}
});
});
I have tried various methods, including creating a globe variable for VendorClient, then after response ajax i'm adding this code VendorClient.ajax.reload(null, false); and get errorr (index):406 Uncaught (in promise) TypeError: Cannot read property 'ajax' of undefined
but it's not working, any ideas?
Try to redraw the table:
$('#getData').DataTable().clear().draw();
or
$('#getData').DataTable().columns.adjust().draw();
or
$('#getData').DataTable().columns.adjust().draw(false);

Datatable ,Javascript and Json

I have a Django Python webapp , i have a function :
def showreport(newrequest) :
rep1 = get_report_data(newrequest,2)
data={['columns':rep1[0],'rows':rep1[1]}
return JsonResponse(data,safe=False)
i call this function from javascript in HTML page , the data return is an array with two elements, 1 represent columns and the other the data.
I want to present in the HTML page the data in a DataTable object , and since the columns and data is dynamic i want to create the DataTable dynamically
In the HTML
In JavaScript
$(document).ready(function () {
$("#showresults").on('click', function(evt) {
evt.preventDefault();
$('#show_loading').show();
$('#theTable').hide();
froms = document.getElementById('startdate').value;
tos = document.getElementById('todate').value;
$.ajax({
type: "POST",
url: 'showreport',
data: {
'start_date' : froms,
'end_date' :tos,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (data, textStatus, jqXHR) {
$('#show_loading').hide();
var rowSet=data['rows'];
var columnset =data['columns'];
$('#theTable').DataTable({
"processing": true,
searching: false,
paging: false,
"bInfo" : false,
columns: [columnset] ,
data: [rowSet]
} );
$('#theTable').show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#show_loading').hide();
alert("Error, please try again!");
}
});
});
});
Now the problem i have is that the Columns are not presented and the data is presenting only 1 row and it is not separated to columns.
In inspect mode , i can see
{"rows": [["Test1", "Test2"],["Test3", "Test4"] etc..., "columns": ["col1","col2"]}
What am i doing wrong.
Thanks,
N
I think you have an array of an array :)
try
change this
columns: [columnset],
data: [rowSet]
to this
columns: columnset,
data: rowSet

How to define a function to modify data submitted to the server on Ajax request

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

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

Categories

Resources