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
Related
I have tried to implement the server side pagination concept for my table (jQuery(v1.12.4),datatable(v1.10.15))
As per the datatable server side pagination documentation
I have enabled serverSide, paging, processing as true and specified the sPaginationType along with the ajax.
In the Custom Data Source Property article, it is mentioned that we need to use dataSrc Option being used as a string to get the data from a different source property, in this case demo but it could be any value, included a nested property by using standard dotted Javascript object notation.
I have used the dataSrc as per the above point ie., "dataSrc": "data" based on my json response.
However the data is not being loaded.
My table loads only the approve button (which i have defined in the columns section) rest of the columns are empty. - convening that the data are not rendered in the table.
Refer Output 2 image.
Since I have used deferLoading first page returns empty data. Refer Output 1 image.
I have referred all the below mentioned articles
Custom data source property dataSrc and pagination issue
Datatables server side processing pagination issue
The code is snippet is shown below, please help
$('#vschildtable').DataTable({
"language": {
"processing": "Please
wait - LOADING SCAN Result...", "
emptyTable " : "
Currently no
data found in this project " }, "
bJQueryUI " : true, "
paging " :
true,
"sPaginationType": "full_numbers",
"processing ": true,
"serverSide": true,
"columns": [{
"defaultContent": "",
"visible": false
}, {
"defaultContent": "",
"visible": false
}, {
"defaultContent": ""
}, {
"defaultContent": ""
}, {
"defaultContent": ""
}, {
data: null,
defaultContent: ' <
button type = "button"
class = "btn-approve label label-link bg-green " > Approve < /button>
' } ], "deferLoading" : 57, "ajax" : { "url" : "emppage?empID=" +
encodeURIComponent(empID) + "&projectId=" +
encodeURIComponent(projectID) + "&subProjectId=" +
encodeURIComponent(subProjectID) + "&pageNo=" +
encodeURIComponent(offset),
type: 'POST',
datatype: "jsonp",
"dataSrc": "data"
}
});
Json response:
[{
"message":"SUCCESS",
"data":"{\"data\":\[{\"projectId\":1,\"subProjectId\":1,\"empID\":765,\"empName\":\"Arjun\",\"empIDVersion\":\"1%3A4.1.4\",\"fkempID\":7781,\"tmpempID\":354999,\"noOfDept\":1,\"rowNo\":1,\"totalnoOfDept\":1},{\"projectId\":1,\"subProjectId\":1,\"empID\":765,\"empName\":\"Arjun\",\"empIDVersion\":\"4.0.18.1\",\"fkempID\":7781,\"tmpempID\":355000,\"noOfDept\":1,\"rowNo\":2,\"totalnoOfDept\":1},{\"projectId\":1,\"subProjectId\":1,\"empID\":765,\"empName\":\"Arjun\",\"empIDVersion\":\"4.2.1\",\"fkempID\":7781,\"tmpempID\":355001,\"noOfDept\":1,\"rowNo\":3,\"totalnoOfDept\":1}\]}"
}]
As far as I can see, there's missing information in the data returned by the server. DataTables expects some specific data (draw,recordsFiltered,etc.) from the server when running in server side mode. You can check here
Furthermore, You should add the data property to each object in the columns array, specifying the name of the data you expect to render in that column, i.e.:
columns:[
{ data:'projectId' }
{ data:'subPorjectId'}
...
]
this tells DataTables what data to show in which column.
Hope it helps!
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.
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.
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.
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 ?