DataTables won't run render function after AJAX call - javascript

I'm using AJAX to get data into my Datatables table. This is something I've done before and it worked fine, but this time I'm running into an issue.
When I run InitializeDatatables JS function, it successfully generates the table and runs the AJAX which reaches the GetDataForTable controller action. However, nothing more happens once the controller action returns. What should happen is the function in "render" section should run but it does not. No error is given either.
As far as I can tell, this setup is very similar to one I had in another project, but I can't find where I'm making a mistake. One difference is that the previous project was on ASP.NET Core 3.0 and this one is on 2.2.
HTML table setup:
<table id="myTable">
<thead>
<tr>
<th>
Important Stuff
</th>
</tr>
</thead>
//Datatables automatically generates the rest of HTML needed
</table>
JS function that runs on page load:
function InitializeDatatables() {
$('#myTable').DataTable({
"lengthChange": false,
"ajax": {
"url": "/Home/GetDataForTable", //controller action runs and returns
"type": "GET",
error: function (error) {
var test = error; //no error is given
}
},
"columns": [
{ "data": null } //"data: null" to access all JSON data in "render" function(data).
],
"columnDefs": [
{
"targets": 0,
"render": function (data) { //function never runs
var test = data;
return '<span>test</span>';
}
},
{"className": "testClass", "targets": 0} //class name is successfully added
]
});
}
Controller action:
[HttpGet]
public JsonResult GetDataForTable()
{
MyModel model = new MyModel();
model.ImportantStuff = _myProcessingService.GetDataFromDB();
return Json(new { data = model });
}

Related

How to get a value of a function from a javascript file to an ASP.NET MVC view?

i am trying to separate my view from java script,in my view im calling a function in js file to create a chart,
Here is my js file and the function:
function pieChartForInterventions(chartID,pieChartData) {
chartID.kendoChart({
dataSource: {
data: pieChartData
},
series: [{
type: "pie",
field: "list",
categoryField: "mm",
padding: 0,
labels: {
visible: true,
}
}],
seriesClick:onDb,
tooltip: {
visible: true,
template: "${ category }"
}
,
legend: {
position: "bottom"
}
});
}
function onDb(e) {
var _clicked = e.category;
}
here is my view:
pieChartForInterventions($("#pieChart"), result);
now the problem is,as you see in my function i have a onDb() function whick invokes when i click on my chart to get the value of what i clicked,i need this value to send it back with a Ajax call via my view,how should i have this value in my view?
Please elaborate a bit more, where exactly in your view do you require this value? OR what do you want to do with this value after receiving it in the view?
If you have something available in javascript, it means you already have it in your “View”, since the only place your javascript logic is executing is in your view.
From your onDb(e) function, you can:
1) Return the value and use it anywhere you need within the view via javascript logic.
In your sepearated js file you may have a function like:
function onDb(e) {
var _clicked = e.category;
return _clicked;
}
Somewhere in your view (.cshtml) you may do something like:
<script type="text/javascript">
// Get 'e' from wherever you need
var requiredValue = onDb(e);
// Any Javascript / JQuery / Ajax logic ...
</script>
2) If the returned value is required at the server side, you can send an AJAX request etc. See the following on how to send an AJAX request (MVC jquery ajax call with input parameter)
==== UPDATE AFTER COMMENT ====
You can access the onDb function the same way as I mentioned in the second code snippet. However, in that case getting the input parameter “e” would require some scripting.
Alternatively, what’s even easier in this scenario is that you can move the “Ajax Call” inside onDb(e) function. Update the onDb(e) function as follows …
function onDb(e) {
var _clicked = e.category;
$.ajax({
type: "POST",
url: '#Url.Action("ControllerName", "ActionName")',
contentType: "application/json; charset=utf-8",
data: { valueToSend: _clicked },
dataType: "json"
});
}
And on your server side you would have some action like:
public class ControllerName : Controller
{
[HttpPost]
public ActionResult ActionName(string valueToSend)
{
//The value you needed is stored in the input paramater 'valueToSend'
//... process however you want and return any ActionResult ...
return Json("success", JsonRequestBehavior.AllowGet);
}
}

redrawing/refilling jquery datatable data set after page change or any other event

I have a jquery datatable in my page which I fill up with data like this:
$(document).ready(function () {
var datatable;
$(document).on("click", ".myBtnClass", function () {
if (datatable != null)
datatable.destroy();
datatable = $('#tableProducts').DataTable({
"pageLength": 50,
"processing": false,
"serverSide": true,
"filter": true,
"bLengthChange": false,
"bSort": false,
"orderMulti": false,
"ajax": {
"url": "/Bulk/LoadData/",
"type": "POST",
"data": {
"username": $(".sellerInput").val(),
"drange": $(".select2").val()
},
"dataSrc": function (data) {
return data.data;
}
}
});
});
});
So as you can see here I'm filling up the datatable with data that my method returns "LoadData" ...
The problem here is in this line:
if (datatable != null)
datatable.destroy();
Every time I destroy the table in order to recreate it with new data, I loose the design of the table, and it becomes deformed and looks ugly after it's destroyed/recreated....
Is there any other way to reload the data into the table without actually calling the destroy() method ?
You could try two different approaches:
1. Destroy/reinstanciate the table
add the option destroy:true in the table's initialization, and remove
if (datatable != null)
datatable.destroy();
This tells datatables to destroy and reinstanciate the table when you call the initalization function on an existing instance.
However, this might still mess up the table's design.
2. Use ajax.reload()
another, perhaps preferable approach, is to reload the data using the url provided in the ajax option:
$('#tableProducts').DataTable().ajax.reload();
Here's more info about the ajax.reload() functionality.

Jquery Datatable Server Side Pagination With External Search field

I have a Jquery Datatable which displays some data and it has an external search field.I am trying to implement Server side pagination with the help of Jquery Datatable plugin.But the problem is,it has an external search field,in which user can select a date(basically month and year) and search for the records.So, every time user opt for a search the datatable need to be refreshed.Can anyone help me on this.
Datatable
var LeaveDetailsTable = $('#LvReprtTable').DataTable({
"pageLength": 5,
"processing": true,
"serverSide": true,"searching": false,"bLengthChange": false,
"ajax": {
"url": "GetLeaveDetails",
"type": "POST",
"datatype": "json",
"data": function (d) {
d.EmpId = empId;
d.UserType = userType;
d.Month = "1";
d.year = "2017";
}
},
"columns": [
{ "data": "_fromdate" },
{ "data": "_todate" },
{ "data": "_strLvType" },
{ "data": "_leavedurationtype" },
{ "data": "_leavedurationtype" },
{ "data": "_leavedurationtype" },
],
"columnDefs": [{
"targets": -1,
"data": data,
"defaultContent": "<button>Click!</button>"
}]
,"language":
{
"processing": "<div class='row text-center waitIconDiv' id='LoadIconDiv'><img alt='Progress' src='~/Content/images/wait_icon.gif' width='50' height='50' id='imgProgLvRprt' /></div>"
},
});
Month and year may vary.
You would need to call the ajax.reload() on the datatable instance in whatever event of whatever element you want :
LeaveDetailsTable.ajax.reload();
which will post the state of datatables with your new parameters that got added in data property to the controller action.
You can also take a look at this article (Server Side Advanced Search using JQuery DataTables) which explains how to send custom parameters to controller action with JQuery DataTables.
To achieve this I recommend you to use jquery onchange method. For example:
$('.input-class').on('change', function () {
$table.fnDraw();
});
Here $table refers the name of your Datatable and fnDraw() is a Datatable function to refresh your table.
And obviously you need to add data from search field to the request. For this, I recommend you going through link below:
datatables

JavaScript: Datatables serverside processing - change values before display

For displaying my data in a table, I use the dataTable plugin. As I have a big amount of data, I use the serverside processing. My problem is, that I have some data fields in my obtained JSON, that I would like to change before i display it in the table.
Example: I get values, whether some equipment is available or not. This is written as "", 0 or 1 in datasbase, for displaying it I would like to convert these values to "Yes" or "No" or "N/A".
To initialise the table I use the following code:
table = $('#table').DataTable({
"ajax": "myurl",
"sPaginationType": "full_numbers",
"sAjaxDataProp":"",
"deferRender": true,
columns: [
{data: 'attributes.0.value'},
{data:'attributes.1.value'},
{data:'attributes.2.value'},
{data:'attributes.3.value'},
{data:'attributes.4.value'}],
});
To bind the conerting function directly in the data array doesn't work (like
{data: convert(attributes.0.value)},
There are some parameters for the datatable plugin, which I tried, but I'm not sure, if they can solve my problems. This is an example from the documentation of the plugin:
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"data": function ( d ) {
d.extra_search = $('#extra').val();
}
}
});
Can I use the data parameter to solve my problems (when I tried this, d is always empty) or it there another possibility to change my values before I integrate them in a table?
You could preprocess the JSON in an ajax.dataSrc function, but since you really just need to modify how the values are shown I would go for column rendering :
columns: [
{ data: 'attributes.0.value',
render: function(data, type, row) {
switch(data) {
case '0' : return 'No'; break;
case '1' : return 'Yes'; break;
default : return 'N/A'; break;
}
},
{ data: 'attributes.1.value' },
{ data: 'attributes.2.value' },
{ data: 'attributes.3.value' },
{ data: 'attributes.4.value' }
]
Use the above render method to each of the column values you need to convert.

How to better define JQuery DataTables column rendering?

We use JQuery DataTables extensively. I am now switching all the app tables to AJAX data source to better support search and to render tables faster.
The problem I am having is how to define data rendering inside my table columns. I do not render only data in the column but I need to have some additional markup in some columns (like <span class="label">data</span> or links, etc.).
This can be done via javascript, here is how I did it. The problem is I don't want to have this column definition syntax for every table in my app. Not two tables are identical, and to support all tables/columns like this it would result in bunch of javascript code for every table. I don't see this as a good practice.
$('.data-table').each(function(){
initialize_ajax_data_tables($(this));
});
function initialize_ajax_data_tables(element)
{
var display_rows = element.attr('data-rows') ? parseInt(element.data('rows')) : 25;
var initial_sort = element.attr('data-sort') ? element.data('sort') : [0, 'asc'];
dataTables = element.DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: base_url+'ajaxprocess/products_data_table.json',
type: 'GET'
},
"columns": [
{ "data": "id" },
{ "data": "product_type_name" },
{ "data": "code" },
{ "data": "name" },
],
"columnDefs": [
{
"render": function ( data, type, row ) {
return '<span class=\"label label-info\">'+ data +'</span>';
},
"targets": 1
},
{
"render": function ( data, type, row ) {
return '<span class=\"label label-success\">'+ data +'</span>';
},
"targets": 2
},
],
"pageLength": display_rows,
"order": initial_sort,
});
dataTables = $.fn.dataTable.fnTables(true);
}
Is there a way to somehow define this column definition/rendering in HTML itself and then pull this in the javascript when initialising DataTables? Or any other way on how to approach this issue?
For sorting rules and pageLength on the DataTables I use data-attributes from the <table> element and that works perfect. This way I define attributes like:
<table id="DataTables_Table_0" class="data-table" data-rows="50" data-sort="[0,"desc"]">
This works fine, but can not use this for columnDefs arrays as render attribute expects function.
I am making some progress and am posting my findings bellow. Maybe some find this useful, but I would still be open to other solutions in case you have a better design.
Currently I have split my code into two three sections:
Main application JS file: common DataTables initialisation code for all the application tables
View: HTML table view generated by the backend and served to the browser. In this view I define table specific properties which are then referenced in in common DataTable init code
Backend AJAX script which serves table data
So to demonstrate this with actual code.
1. Main initialisation code
$('.data-table').each(function(){
initialize_data_tables($(this));
});
function initialize_data_tables(element)
{
if(!(element instanceof jQuery)) element = $(element);
var table_defs = element.attr('data-table-def') ? eval(element.data('table-def')) : [];
dataTables = element.DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: table_defs.url,
type: 'POST'
},
"columns": table_defs.columns,
"pageLength": table_defs.rows,
"order": table_defs.sort,
});
dataTables = $.fn.dataTable.fnTables(true);
}
2. The HTML view
Here I define specific JS object for table definition, column definition and so on. Every table in app has specific definition. This structure also allows me to have multiple data tables on the view at the same time and reference the right JS object with table properties definition.
<script type="text/javascript">
var tableDef = {
url: "<?= Uri::create('utilities/ajaxprocess/products_data_table.json') ?>",
columns: [
{ "data": "id" },
{ "data": "product_type_name", render: function ( data, type, row ) {
return '<span class=\"label label-info\">'+ data +'</span>';
}
},
{ "data": "code" },
{ "data": "name" },
],
rows: 50,
sort: [ 0, 'desc' ]
};
</script>
<table class="data-table" data-table-def="tableDef”>...</table>
3. The backend
No need to paste my code here. Just functions that query my database and prepare data to be served via AJAX to DataTables.
Following your idea I would say try to define the render methods somewhere and bind them through data attributes.
This solution would be rather easy to test, but I don't think you can work around the columnDefs problematic.

Categories

Resources