Jquery Datatable filter duplicate rows - javascript

$(document).ready(function () {
var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'paging': false,
'bFilter': false,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
return JSON.stringify( d );
}
}
});
table.column( 3 ).data().unique();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdn.datatables.net/1.10.9/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
</table>
I am trying to use datatable unique function but I am unable to execute it. Actually I want to remove the duplicate data I am using dynamic ajax data.
table
.column( 3 )
.data()
.unique();
Like in this example I want to filter out the cities, Kindly suggest me what I am doing wrong and is there any other way, I couldnt found any other answers in stackoverflow or may be unable to understand. I am using version 1.10.9

Take notice of the actual purpose of unique :
Create a new API instance containing only the unique items from a the
elements in an instance's result set.
Unique returns a filtered set of unique items, it does not filter the rows shown in the table. Since you want to show rows where duplicated data is removed I will suggest you filter out the duplicates in the dataSrc callback. You do not provide details about the JSON, but here is an example with one of the "canonical" JSON datasets, where duplicated offices is filtered out. It simply uses javascripts Array.filter on the returned data array :
var table = $('#example').DataTable({
ajax: {
url: 'https://api.myjson.com/bins/avxod',
dataSrc: function(json) {
var offices = [];
return json.data.filter(function(item) {
if (!~offices.indexOf(item.office)) {
offices.push(item.office);
return item;
}
})
}
},
columns: [
{ data: 'name' },
{ data: 'position' },
{ data: 'office' },
{ data: 'salary' }
]
})
demo -> http://jsfiddle.net/cbcqdj7h/

Execute unique there just return nothing.
If you just want get a unique data after you get real data.
var table = $('#example').DataTable({
...,
drawCallback:function(){
var a = table.column( 3 ).data().unique();
console.log(a);
}
})
If you want filter data without the same value.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'paging': false,
'bFilter': false,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
// TODO do some thing here to filter value
return JSON.stringify( d );
}
}
});
And DataTable doc https://datatables.net/reference/option/ajax

Related

DataTables Requested unknown parameter 'PageId'

I am running into the following error trying to load DataTables Objects data (https://datatables.net/manual/data/):
DataTables warning: table id=report-table - Requested unknown parameter 'PageId' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/
Below is example json data I am recieving from my C# SchemaReport/GetReportJson controller and being used in JQuery ajax success callback to initialize my DataTables:
[{"PageId":"foo","SchemaName":"foo","Name":"foo","LastModified":"foo","LastModifiedUser":"foo"}]
DataTables HTML:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
JQuery ajax and DataTables init script:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
data: data,
columns : [
{
data : 'PageId'
},
{
data : 'SchemaName'
},
{
data : 'Name'
},
{
data : 'LastModified'
},
{
data : 'LastModifiedUser'
}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'csv',
text: 'Download CSV',
filename: 'report-file'
},
{
extend: 'excel',
text: 'Download Excel',
filename: 'report-file',
title: ''
},
]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
I noticed that after acknowledging the error DataTables loads as following and stating 134 entries:
134 matches the character count of the json data (provided in answer). For some reason it appears DataTables is not seeing the json object and parsing individual characters? Just not sure why it would be doing this?
Your columns block should be:
columns : [
{
'data' : 'PageId'
},
{
'data' : 'SchemaName'
},
{
'data' : 'Name'
},
{
'data' : 'LastModified'
},
{
'data' : 'LastModifiedUser'
}
],
You should also be sending your data from the Controller like this:
return Json(schemaData);
You do not need to serialize your data when you are returning a JSON since this will already return data in JSON format and if you use JsonConvert.SerializeObject then you are converting it twice which the DataTable plugin does not like.

JQuery Datatable Reload From Server MVC

I have a Datatable of JQuery generated at first-page load. I am trying to refresh it according to the selected criteria from the selectlist.
My Datatable initialized first like the following code.
<table class="table table-striped table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Select All <input type="checkbox" class="checkbox" id="chkBoxAll"></th>
#foreach (System.Data.DataColumn col in Model.DataTypesTable.Columns)
{
<th> #col.Caption</th>
}
</tr>
</thead>
<tbody>
#foreach (System.Data.DataRow row in Model.DataTypesTable.Rows)
{
<tr>
<td> <input type="checkbox" class="checkbox" name="chkBox" value="#row.ItemArray[0]"></td>
#foreach (var cell in row.ItemArray)
{
<td>
#cell.ToString()
</td>
}
</tr>
}
</tbody>
</table>
<script>
$(document).ready(function() {
$('#dataTable').DataTable();
});
</script>
It initializes well at first. However, when I try to reload it on the selectlistchange event, it doesn't reload anything and displays an error like this.
DataTables warning: table id=dataTable - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'html',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
console.log(result);
$("#dataTable").DataTable({
destroy: true,
data: result,
columns: [
{ data: "Id", name: "Id" },
{ data: "Data Name", name: "Data Name" },
{ data: "Description", name: "Description" },
{ data: "Device Type", name: "Device Type" }
], columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Controller:
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
var json = this.Json(new { data = dt }/*, _jsonSetting*/);
return json;
}
My data is like below from the developer tools:
Please help me out to resolve the issue... Thanks in advance.
After long tries and losing hairs.. I have found a solution clear and add the rows again instead of destroy command. Here is the solution below.
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'json',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
var dataTable = $("#dataTable").DataTable();
dataTable.clear().draw();
$.each(result, function myfunc (index, value) {
// use data table row.add, then .draw for table refresh
dataTable.row.add([
'<input type="checkbox" class="checkbox" name="chkBox" value="' + value.Id + '">',
value.Id,
value.DataName,
value.Description,
value.DeviceType
]).draw();
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Also, it is important to return a json object from the controller action.
PS. If the Json Object has an initial tag like data, you may need to change the looping value.Id to value.data.Id. But it is better to not use any tag.
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
var json = this.Json(dt , _jsonSetting);
return json;
}

Appending Rows to a DataTables Grid

I'm trying to add <tr/> tags dynamically to a DataTable, but I didn't find actual good documentation on how the "adding TR process" is supposed to work. I have this as my DataTables setup:
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
.on("row-reordered", function (e, diff, edit) {
for (var i = 0; i < diff.length; i++)
{
..
}
});
I'm getting the definition of the item in the grid from an MVC action method as an HTML string, via a jQuery AJAX statement:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
var $body = $("#Grid tbody");
$body.append(d);
}
});
The "d" parameter is the HTML for a row; I'm appending it to the body. That adds correctly and but doesn't have the row reorder functionality enabled then. What is the proper way to append to a DataTable, then re-enable whatever functionality?
Use row.add() API method to add a new row instead of appending to the table body.
If d contains string in the following format <tr>...</tr>, you could just use $("#Grid").DataTable().row.add($(d).get(0)) to add a new row.
For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().row.add($(d).get(0)).draw();
}
});
See this example for code and demonstration.
The best option is to use Datatables API's to add rows to the table. As indicated in the previous response you can use either row.add() or rows.add(). The data needs to be in a data structure that matches your Datatables data structure config, ie, arrays or objects.
However it looks like you are receiving HTML structured data and appending directly to the table. In this case Datatables is not aware of the added data. You will need destroy (destroy()) the Datatables table, append your data then re-init Datatables. For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().destroy();
var $body = $("#Grid tbody");
$body.append(d);
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
}
});

DataTables.js Requested unknown parameter when adding row

I have a predefined datatable on my page that is populating from data with an ajax call. After these values are on the page the user needs an ability to add rows by clicking a button, kind of like an audit log. However, every time I go to add a row I get the error
"DataTables warning: table id=DataTables_Table_0 - Requested unknown
parameter 'data1' for row 2, column 0."
I have been up and down the internet and cannot figure this out. Help please.
I have the table variable defined globally so everyone has access to it
var escalationTable;
and then a function that calls my ajax to populate said table.
function populateTable(var1, var2, var3, var4, var5, var6, var7) {
$.ajax({
dataType: 'json',
//data: id,
type: 'GET',
async: false,
url: baseUrl + 'rest/partUrl/action?var1=' + var1 + '&var2=' + var2 + '&var3=' + var3 + '&var4=' + var4,
success: function (data) {
if (data) {
escalationTable = $('.escalationTable').DataTable({
data: data,
columns: [
{
data: "data1" ? "data1" : null
},
{
data: "data2" ? "data2" : null
}, {
data: "data3" ? "data3" : null
}
],
bSort: false
});
}
},
error: function (request, status, error) {
showErrorMessage(request);
}
});
}
html
<table class="table escalationTable col-md-12" style="width:100%;">
<thead>
<tr>
<th name='esId' scope="col">#</th>
<th name='esUser' scope="col">User</th>
<th name='esDate' scope="col">Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and then my click looks like this
$('.assignToSelf').on('click', function () {
var rowNode = escalationTable
.row.add({
"esId": 'ffffff',
"esUser": 'dfsdfsdf',
"esDate": 'fffff'
})
.draw(false)
.node();
})
The answer to this question would be naming the fields in the add the same as the data that is going into the field. Not based on the name of the field.
$('.assignToSelf').on('click', function () {
var rowNode = escalationTable
.row.add({
"data1": 'ffffff',
"data2": 'dfsdfsdf',
"data3": 'fffff'
})
.draw(false)
.node();
})

DataTables do not send ajax request at the initialization

How to use dataTables to instantiate the table does not load data (server mode),then loading data when i click on a button.If serverSide is set to true at initialization, the table will automatically send an ajax request, then render the data, which is not what I want !:(
You should use "iDeferLoading" : 0 in DataTables parameters, when you initialize it:
var table = $("#table").dataTable({
"bProcessing": true,
"bServerSide": true,
"iDeferLoading": 0,
"sAjaxSource": service_url,
"sServerMethod": "POST",
...
...
(or "deferLoading":0 for newer DataTables versions, 1.10 and above),
and then add the event to your button:
$("#button").on("click", function (event) {
$('#table').dataTable().fnDraw();
});
https://datatables.net/examples/server_side/defer_loading.html
in a similar situation, this is how I did it.
<script>
$(function ($) {
$("#tbl").DataTable({columns:[{data:"id"}, {data:"text"}], dom: "tB", buttons: [{ text: "Load Me", action: function (e, dt, node, config) { loadme(e, dt, node, config); } }] });
}
);
// // parameters are passed from the datatable button event handler
function loadme(e, dt, node, config) {
parms = JSON.stringify({ parm1: "one", parm2: "two" });
$.ajax({
// my test web server that returns an array of {id:"code field", text:"country namee"}
url: "WebService1.asmx/GetAList",
data: JSON.stringify({ s: parms }),
type: 'post',
contentType: "application/json; charset=utf-8",
dataType: "json",
// this is just away of passing arguments to the success handler
context:{dt:dt, node:node},
success: function (data, status) {
var contries = JSON.parse(data.d);
for (var i = 0; i < contries.length; i++){
this.dt.row.add(contries[i], "id", "text");
this.dt.draw();
}
},
error: function (one, two) {
debugger;
}
});
}
</script>
</head>
<body>
<div style="width:500px">
<table id="tbl">
<thead>
<tr>
<th>Code</th>
<th>Contru</th>
</tr>
</thead>
<tbody></tbody>
<tfoot></tfoot>
</table>
</div>
</body>
After looking at the source code for half a day, I finally found a solution. First I needed a custom parameter called firstAjax and set it to false. like this:
$("#example").DataTable({
serverSide: true,
ajax: {
url: 'your url'
},
firstAjax: false
});
Then I changed the
_fnReDraw (settings); //in datatables.js line 4717
to
if (settings.oInit.firstAjax) {
_ fnReDraw (settings);
}
If the compressed js file(datatables.min.js), you should find _fnReDraw function corresponding alias.
I found the solution, in the initialization make like this, with the "oLanguage":
$('.table').dataTable({
oLanguage: {
sUrl: ""
}
});
After initialize datatables with ajax, use this simple line to call ajax for get data:
$('#table').DataTable().ajax.reload();
this code may not working with old versions of datatables.
Download latest version: https://datatables.net/download

Categories