Im wondering if it is possible to minimize my code by having a common JS file, As there will be many datatables around my application..
All the Datatables will have same theme only difference will be of data.
Like this script i have
var oTable = $('#ManageForms').dataTable({
"aoColumns": [
/* ID */ {
"bVisible": false,
"bSortable": false,
"bSearchable": false
},
/* Form Name */ null,
/* Form Path */ null,
/* Form CI Path */ null,
/* Actions */ null
],
"bServerSide":true,
"bProcessing":true,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
//"bFilter":true,
//"sServerMethod": "POST",
"sAjaxSource": "{{base_url()}}admin/configurations/listForms_DT/",
"iDisplayLength": 25,
"aLengthMenu": [[2, 25, 50, -1], [2, 25, 50, "All"]],
/*"sEcho": 1,
"columns":[
{data:"FormName"},
{data:"FormPath"},
{data:"FormCIPath"},
{ "data": null,
"defaultContent": "<a href='#editBtnModal' class='editBtnFunc' ><i style='color: #666666' class='fa fa-pencil fa-fw fa-2x'></i></a><a href='#' id='deleteBtn'><i style='color: #ff0000' class='fa fa-times fa-fw fa-2x'></i></a>",
"targets": -1
}
],*/
'fnServerData' : function(sSource, aoData, fnCallback){
$.ajax ({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
}); //end of ajax
},
'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$(nRow).attr("data-id",aData[0]);
return nRow;
}
});
i guess everything will be same except the sAjaxSource": "{{base_url()}}admin/configurations/listForms_DT/",
and
"aoColumns": [
/* ID */ {
"bVisible": false,
"bSortable": false,
"bSearchable": false
},
/* Form Name */ null,
/* Form Path */ null,
/* Form CI Path */ null,
/* Actions */ null
],
so instead of copy pasting the code again and again on every page of datatables. is there any way i put this code in single common.js file and send the parameters for specific datatable.
You should put your code in a function which could be call in each specific case with the url needed as param:
function getData(url){
// ...
"sAjaxSource": url
// ...
}
this function can be in a common js and then use in any other code that is after you import this file.
The array in aoColumns can also be passed as param as the other field.
Related
i am trying to create a filter function from my datatables, how can i post the value that i want coming from the javascript to php using the datatables function?
here is my sample code from my datatables
var oTable = $('#datatables').DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": base_url + "link",
"fnServerParams": function (data) {
data.filter_start_date = $('#filter_start_date').val();
console.log(data);
},
dom: 'lBfrtip',
buttons: [
'excel'
],
"lengthMenu": [[10, 20, 50, 100, 300, -1], [10, 20, 50, 100, 300, "All"]],
"pagingType": "full_numbers",
"language": {
"paginate": {
"previous": 'Prev',
"next": 'Next',
}
},
"bAutoWidth": false,
"aaSorting": [[ 0, "desc" ]],
});
and the data.filter_start_date value is i want it to be post from my php. thank you in advance, i am just really stuck with this problem or am i just doing it wrong.
On php you will get a param filter_start_date which will be sent on every datatables ajax request. Just use it to filter your results.
And in javascript you can do something like this to reload the table
$('#filter_start_date').change(function() {
oTable.ajax.reload();
});
EDIT:
Here's exactly how I use it:
$('#table').DataTable({
//configs
ajax: {
url: baseUrl('/ajax/load-docs'),
type: 'post',
data: function(d) {
d.initial_date = $('#initial_date').val();
}
}
});
and in php
$date = $this->getParam('initial_date'); //getParam from Zend_Framework Controller
in your case you can use $_POST['filter_start_date']
i created a table with jquery datatables. when I want to filter my table with search bar, the browser gives me an alert DataTables warning: table id=grid - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
this is my code :
$("#grid").dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"searching": true,
"language": {
"url": "/translate/datatables.fa-IR.json"
},
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax": {
"url": serviceBase + "/Auth/Admin/SearchOrders2/",
"type": "GET",
'beforeSend': function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorageService.get("authorizationData").token);
}
},
"columns": [
{ "data": "customerContact", "orderable": true },
{ "data": "isDone", "orderable": true },
{
"mRender":
function (data, type, row) {
var xxx = $scope.name1 = $filter("jalaliDateFromNow")(row["createdDate"]);
return "<span>" + $filter("jalaliDateFromNow")(row["orderCreationTime"]); +'</span>';
}, "orderable": true
},
{ "data": "totalPrice", "orderable": true },
{ "data": "count", "orderable": true },
{ "data": "description", "orderable": true },
{
"mRender": function (data, type, row) {
return '<button class="btn btn-sm btn-circle green tooltips" disabled="disabled"><i class="fa fa-check"></i><span>جزئیات</span></button>'
},
"orderable": false
}
],
"order": [[0, "desc"]]
});
which part of my code is wrong?
I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC
I am using jquery datatables.net and I have a table with information. In the one column I have true or false values for whether the user is active or not. I am trying to get it so when the value is false, highlight the value. Right now my code for my table settings looks like this:
//Settings for datatable
$('#userTable').DataTable({
"jQueryUI": true,
"serverSide": true,
"ajax": {
"type": "POST",
url: "/Management/StaffGet",
"contentType": 'application/json; charset=utf-8',
'data': function (data) { console.log(data); return data = JSON.stringify(data); }
},
"columns": [
{ "data": "employeeNumber" },
{ "data": "firstName" },
{ "data": "lastName" },
{ "data": "role" },
{
"data": "active",
},
{
"data": "employeeNumber",
"render": function (data, type, full, meta)
{
return 'Edit | Delete ';
}
}
],
"order": [[ 0, "asc"]],
"paging": true,
"deferRender": true,
"processing": true,
"stateSave": false,
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"pageLength": 10,
"pagingType": "simple_numbers",
"searching": false,
"createdRow": function ( row, data, index ) {
if (data[4] == "false" ) {
$('td', row).eq(5).addClass('highlight');
}
}
});`
Then my code for css is:
`<style type="text/css">
td.highlight {
font-weight: bold;
color: red;
}
</style>`
I feel like there is a problem with the setting on the column, any help is appreciated.
Try
$('#userTable').DataTable({
...
"createdRow": function( row, data, dataIndex ) {
//console.log(data[4]);
if ( data[4] == "false" ) {
//console.log($(row).find("td").eq(4).html());
$(row).find("td").eq(4).addClass( 'highlight' );
}},
...
The commented log statements are in there to check you are getting and comparing the correct data.
Tested with datatables 1.10.1
I have a jQuery dataTable coded up like so:
$("#my-datatable").dataTable( {
"bProcessing" : true,
// Commenting out next line
//"sDom" : 't',
"sAjaxSource" : "some/url/on/my/server",
"sAjaxDataProp" : "",
"bDestroy" : true,
"fnServerData" : function(sSource, aoData, fnCallback) {
aoData.push({
"name" : "asking",
"value" : "yes"
});
request = $.ajax({
"dataType" : "json",
"type" : "GET",
"url" : sSource,
"data" : aoData,
"success" : fnCallback
});
},
"aoColumns" : [
{
"mDataProp" : "name"
},
{
"mDataProp" : "expr"
},
{
"mDataProp" : "seq"
}
]
});
Notice the line that commented out. When this code runs as-is, the table renders beautifully. Unfortunately, it displays lots of stuff that I don't want displayed, such as pagination information, a search bar, etc.
After reading the docs and following the examples, I'm convinced that the line that is commented-out is what I need to configure the dataTable so that only the table itself renders/displays.
But, when I comment it out, I get an error in Firebug and no data populates my table:
TypeError: an is undefined
[Break On This Error]
for ( var i=0, iLen=an.length ; i<iLen ; i++ )
It seems too be complaining about jQuery.dataTables.js line 2895. Can anybody spot why this is happening? Is my sDom attribute not configured correctly? Remember, I just want the table and its headers to draw (and all the data in it). Thanks in advance!
When setting "bProcessing": true, you have to make sure the 'r' is defined inside the sDom, otherwise the error will be generated.
Example :
var oTable = $('#example').dataTable( {
"bProcessing": true,
"iDisplayLength": 10,
"bLengthChange": false,
"bFilter": false,
"aoColumnDefs": [{ "bSortable": false, "aTargets": [ 0, 4, 5 ] }],
"sDom": "t<'row-fluid'<'span4'i><'span8'pP>r>",
"sPaginationType": "bootstrap",
"oLanguage": { "sLengthMenu": "_MENU_ records per page" }
});
I think what you are after is this perhaps
http://datatables.net/examples/basic_init/filter_only.html
you could leave sDom: T (the default) and manually turn everything off
"bPaginate": false,
"bLengthChange": false,
"bFilter": true,
"bSort": false,
"bInfo": false,
"bAutoWidth": false