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.
Related
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.
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
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.
I want to use mrender for 2 data variables . my ajax data source is like:
{"campaigns":{"campDetails":[{"campaign_id":"1012","campaign_name":"RP - Axe Sample (Submit)","campaign_desc":"Get your FREE sample of Axe Deodorant!","cost":"$0.00","epc":"$0.14","cr":"8.01","payout":"$1.25","url":"http:\/\/www.adworkmedia.com\/go.php?camp=1012&pub=24043&sid=","image":"http:\/\/www.adworkmedia.com\/image.php?pub=24043&id=3061&sid=","categories":"Email & Zip Submits, Survey \/ Freebie \/ Sweepstakes","incent":"Incent,No Points,No Cash","countries":"US","teaseText":"Get a Sample of Axe Deodorant! Details Apply!","teaseDesc":"Get a Sample of Axe Deodorant with your participation!","conversion_point":"E-mail Submit","device_type":"All Devices (Mobile Friendly)"},{},{}....]}}
so I have used sAjaxDataProp for rendering the data in the form of
$(document).ready(function() {
$('#example').dataTable( {
"order": [[ 2, "desc" ]],
"sAjaxSource": "http://localhost/survey/justearn/index/dist/downloadfile/php/",
"processing": true,
"sAjaxDataProp": "campaigns.campDetails",
"aoColumns": [
{ "mData": "campaign_name" },
{
"mData": "url",
"mRender": function(data, type, val) {
switch (type) {
case 'display':
return '' + url + '';
break;
// optionally, add case statements for 'sort', 'filter', and 'type'
default:
return data.bar;
break;
}
}
},
{ "mData": "cr" }
]
} );
} );
}
I am able to get campaign_name and cr columns while processing but the 2nd columns seems to have an error, thats because i want to use 2 mData for the same mRender function
I tried using
{"mData": "foo",
"mData2": "bar",
"mRender": function(data, data2){
return 'bar'; //
}
}
Since I am new to array could you help me solve the 2nd column so I may be able to mRender it,you can use the ajax source i posted above, I want the two mData variables for the second column as "url" and "campign_desc" using mRender from the ajax data source above.
If you debug your code using Firebug you'd be able to see that val contains the row data, so displaying it if the way you want is simply a case of:
{
'mRender': function (data, type, val) {
return ' + val[1] + '';
}
}
Using Datatables with AJAX / POST, I initialize like this, where experiment_list is a list, and $("#type") is a selector menu.
var my_table = $('#my_table').DataTable( {
"ajax": {"url": "/experiment_data/", "type":"POST", "data": {"experiments": experiment_list, "type": $("#type_selector").val() } },
"dom": '<"top">rt<"bottom"fp><"clear">',
} );
The problem I am having is that "type" is at initialization to the selector menu value, and changing the value after that and reloading the data, does not change the value in the "ajax" method.
$("#type_selector").change(function () {
console.log($("#type_selector").val());
position_table.ajax.reload()
});
The API Documentation only has .url() for a dynamic method, which would mean either using GET (which is not very good for object type data) or rewriting views for each selector 'type' (and changing the url on select).
Is there a way to update the Data load of the Post request Dynamically?
Did you try with the sample request they provide ?
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "/experiment_data/",
"data": function ( d ) {
d.experiments = experiment_list;
d.type = $("#type_selector").val();
}
}
});
If it fails, can you provide the log of Firebug please ?