jquery datatable does not get initialized with given response - datatables

I want to initialize data table with my generated response
my response looks like this
{data: Array(3), status: true}
data : Array(3)
0 : {countryId: 1, countryName: "sampleCountry", countryShortCode: "sampleCode", status: "yes"}
1 : {countryId: 2, countryName: "pakistan", countryShortCode: "pak", status: "yes"}
2 : {countryId: 3, countryName: "sample2", countryShortCode: "pak", status: "yes"}
please look at my html
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
please look at my datatable initialization
$.ajax({
url : url,
type:"get",
contentType:'application/json; charset=utf-8',
dataType: 'json' ,
async: false,
success:function(response)
{
alert(response.data);
$('#countryTable').DataTable( {
"fnRowCallback" : function(nRow, aData, iDisplayIndex){
$("td:first", nRow).html(iDisplayIndex +1);
return nRow;
},
destroy: true,
mydata: response.data,
columns: [
{ mydata:'countryId'},
{ mydata:'countryName'},
{ mydata:'countryShortCode'}
]
} );
console.log(response);
}
});
after initialization data table shows as No data available in table but table gets initialized with datatable plugin .
data is not coming into table.
what went wrong in my code please help me.

The code looks fine, you just need to change mydata to data, like this:
var response = {
data: [{
countryId: 1,
countryName: "sampleCountry",
countryShortCode: "sampleCode",
status: "yes"
},
{
countryId: 2,
countryName: "pakistan",
countryShortCode: "pak",
status: "yes"
},
{
countryId: 3,
countryName: "sample2",
countryShortCode: "pak",
status: "yes"
}
],
status: true
}
$('#countryTable').DataTable({
"fnRowCallback": function(nRow, aData, iDisplayIndex) {
$("td:first", nRow).html(iDisplayIndex + 1);
return nRow;
},
destroy: true,
data: response.data,
columns: [{
data: 'countryId'
},
{
data: 'countryName'
},
{
data: 'countryShortCode'
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Related

how to implement (Server-side) SearchPanes of DataTables in mvc core

I need an example of a (Server-side Procssing) SearchPanes implementation of DataTables in mvc core
In the link I have an example of implementing datatables including operations such as Sorting, pagination and search but about the implementation of searchPanes please help me
You could use Juery Ajax to call the MVC action method and load data, then, setting the JQuery DataTable's "searchPanes", "columnDefs" and "dom: 'Pfrtip'," property to implement the SearchPanes function. Sample Code as below:
Code in the Action method:
[HttpPost]
public JsonResult GetData()
{
List<Employee> employees = new List<Employee>()
{
new Employee(){ DT_RowId="row_1", First_Name="Tiger", Last_Name="Nixon", Position="System Architect", Email="t.nixon#datatables.net", Office="Edinburgh", Extn="5421", Age="61", Salary="320800", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_2", First_Name="Garrett", Last_Name="Winters", Position="Office Manager", Email="t.nixon#datatables.net", Office="London", Extn="7580", Age="61", Salary="13800", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_3", First_Name="Timothy", Last_Name="Mooney", Position="System Architect", Email="t.nixon#datatables.net", Office="San Francisco", Extn="5384", Age="61", Salary="85675", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_4", First_Name="Unity", Last_Name="Butler", Position="Marketing Designer", Email="t.nixon#datatables.net", Office="San Francisco", Extn="9421", Age="61", Salary="452500", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_5", First_Name="Vivian", Last_Name="Harrell", Position="Financial Controller", Email="t.nixon#datatables.net", Office="London", Extn="7439", Age="61", Salary="67500", Start_date="2011-04-25"},
};
return Json(employees);
}
Code in the View Page:
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/searchpanes/1.1.1/css/searchPanes.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/select/1.3.1/css/select.dataTables.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/searchpanes/1.1.1/js/dataTables.searchPanes.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.1/js/dataTables.select.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
JQuery script:
<script>
$(document).ready(function () {
$(function () {
$.ajax({
type: "POST",
url: "/Home/GetData",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function OnSuccess(response) {
$("#example").DataTable(
{
bLengthChange: true,
bFilter: true,
bSort: true,
bPaginate: true,
data: response,
searchPanes: {
columns: [2, 5],
layout: 'columns-2',
},
columnDefs: [{
searchPanes: {
show: true
},
targets: [5]
}],
dom: 'Pfrtip',
columns: [{
'data': null, render: function (data, type, row) {
// Combine the first and last names into a single table field
return data.first_Name + ' ' + data.last_Name;
}
},
{ 'data': 'position' },
{ 'data': 'office' },
{ 'data': 'extn' },
{ 'data': 'start_date' },
{
'data': 'salary',
render: $.fn.dataTable.render.number(',', '.', 0, '$')
}
]
});
};
});
</script>
The output as below:
More detail information, please check the following links:
Populate jQuery DataTables in Asp.net MVC
JQuery DataTables SearchPanes
DataTables SearchPanes Examples
Your server's response JSON should have an object named searchPane; the
content of this object is something like this:
$searchPanes['options'][$key][]=["label" => $v['label'], "total" => $v['total'], "value" => $v['value'], "count" => 0];

click and change events are not working for Angular 6 Datatables Responsive extension

I use Angular 6 datatables for show data in the frontend. I used responsive extension to show more data as described in
https://l-lin.github.io/angular-datatables/#/extensions/responsive
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th>Category Name</th>
<th>Description</th>
<th>Is Enable</th>
<th>Sub Categories</th>
<th>update</th>
<th>delete</th>
<th>Extra Data</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of vehicleCategoryData; let i = index">
<td>{{data.categoryName}}</td>
<td>{{data.description}}</td>
<td>{{data.isEnable}}</td>
<td>{{data.subCategory.length}}</td>
<td><i class="fa fa-edit" (click)="update(i)"></i></td>
<td><i class="fa fa-trash-o" (click)="delete(i)"></i></td>
<td>{{data.extraData}}
</tbody>
</table>
also my dtOptions are defined as follows.
dtOptions: any = {
pagingType: 'full_numbers',
pageLength: 5,
columns: [{
title: 'Category Name',
data: 'categoryName'
}, {
title: 'Description',
data: 'description'
}, {
title: 'Is Enable',
data: 'isEnable'
},{
title: 'Sub Categories',
data: 'sub'
},
{
title: 'update',
data: 'up'
},
{
title: 'delete',
data: 'del'
},
{
title : 'Extra Data',
data : 'sc',
className : 'none'
}],
responsive: true
};
So everything works fine. but
(click)="update(i)"
(click)="delete(i)"
events are not working. How can i solve this problem. Any suggestions?
I solve this problem by using the listHiddenNodes function.
First i imported the Responsive variable in the component
import Responsive from 'datatables.net-responsive';
then i put this code on the dtOptions
this.dtOptions = {
responsive: {
details: {
renderer: Responsive.renderer.listHiddenNodes()
}
},
};
That's all!

jQuery Datatables column count error - Requested unknown parameter '0' for row 0, column 0

This is a very common question, I'm aware. But I spent almost a day because I can't spot the error I have to post this. Can anyone see a mistake?
Markup :-
<table class="table align-items-center table-flush py-3" id="inquiry-select-table">
<thead class="thead-light">
<tr>
<th scope="col" style="display:none">ID</th>
<th scope="col" style="display:none">Version</th>
<th scope="col" style="display:none">Created Date</th>
<th scope="col" style="display:none">Created Time</th>
<th scope="col" style="display:none">Updated Date</th>
<th scope="col" style="display:none">Updated Time</th>
<th scope="col" style="display:none">Client ID</th>
<th scope="col">Client Name</th>
<th scope="col">Knowledge Source</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS :-
var inquirySelectTable;
var inquirySelectTableColumns = [{
data: "id"
},
{
data: "version"
},
{
data: "createdDate"
},
{
data: "createdTime"
},
{
data: "updatedDate"
},
{
data: "updatedTime"
},
{
data: "clientId"
},
{
data: "clientName",
defaultContent: "",
className: "all"
},
{
data: "knowledgeSource",
defaultContent: "",
className: "all",
render: function (data, type, row) {
switch (data) {
case 'WOM':
return 'Word of mouth';
case 'PAPER':
return 'Paper Article';
case 'FB':
return 'Facebook';
case 'GOOGLE':
return 'Google Ad';
case 'EMAIL':
return 'Email';
case 'SMS':
return 'SMS';
default:
return 'Other'
}
}
},
{
data: "description",
defaultContent: "",
className: "all"
}
];
var inquiryColumnDefs = [{
"targets": [0, 1, 2, 3, 4, 5, 6],
"visible": false,
"searchable": false
}];
var tableSizeFromFive = [
[5, 10, 15, 25 - 1],
[5, 10, 15, 25, "All"]
];
$(document).ready(function () {
inquirySelectTable = $('#inquiry-select-table').DataTable({
pagingType: "numbers",
responsive: true,
lengthMenu: tableSizeFromFive,
columnDefs: inquirySelectTableColumns,
columns: inquiryColumnDefs,
});
$.get("inquiries/getAllInquiries", function (data, status) {
console.log(data);
setGridData(inquirySelectTable, data);
});
});
function setGridData(table, data) {
table.clear();
table.rows.add(data).draw();
if (table.data().count() > 0) {
$(".table-responsive").removeClass("disabled");
} else {
$(".table-responsive").addClass("disabled");
}
}
The data received from the server :-
The error I'm getting is :-
According to https://datatables.net/manual/tech-notes/4, since I'm getting an Integer as the parameter it means the column count does not match with the row count. But it seems ok to me. Does anyone see something I missed?
Seems like you've swapped columnDefs and columns:
columnDefs: inquirySelectTableColumns,
columns: inquiryColumnDefs,
Interchange them and it'll work fine:
columnDefs: inquiryColumnDefs,
columns: inquirySelectTableColumns,
Example fork:
http://jsfiddle.net/bsf69o04/

How to select All checkboxes based on condition with Vue.js

I am trying to select checkboxes based on some condition.
Select all checkboxes (select all checkboxes)
select all unread (select all unread where data array has status of
unread)
select all read (select all read where data array has status of read)
I am able to select all checkboxes on checkbox click,but unable to select it with links
I also need to fetch the ids of selected checkboxes,so i can perform action against these selected checkboxes.
Can you guys please have a look at this.
new Vue({
el: "#app",
data: {
selected: [],
messages: [{
id: 1,
text: "Learn JavaScript",
status: 'read'
},
{
id: 2,
text: "Learn Vue",
status: 'unread'
},
{
id: 3,
text: "Play around in JSFiddle",
status: 'read'
},
{
id: 4,
text: "Build something awesome",
status: 'unread'
}
]
},
methods: {
},
computed: {
selectAll: {
get: function() {
return this.messages ? this.selected.length == this.messages.length : false;
},
set: function(value) {
var selected = [];
if (value) {
this.messages.forEach(function(item) {
selected.push(item.id);
});
}
this.selected = selected;
}
}
},
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<h2>Message App:</h2>
<table class="table">
All,
Read,
Unread,
<thead>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th>Status</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in messages">
<td><input type="checkbox" v-model="selected" :value="item.id"></td>
<td>{{ item.status }}</td>
<td>{{ item.text }}</td>
</tr>
</tbody>
</table>
</div>
You might want to use click event on a element:
All,
and in javascript code:
methods: {
selectAllHandler() {
if (this.selected.length) {
this.selected = []
} else {
this.selected = this.messages.map(item => item.id);
}
}
}
Your Javascript:
new Vue({
el: "#app",
data: {
selected: [],
messages: [{
id: 1,
text: "Learn JavaScript",
status: 'read'
},
{
id: 2,
text: "Learn Vue",
status: 'unread'
},
{
id: 3,
text: "Play around in JSFiddle",
status: 'read'
},
{
id: 4,
text: "Build something awesome",
status: 'unread'
}
]
},
methods: {
selectAll() {
this.selected = this.messages.map((message) => message.id);
}
}
})
Your HTML:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<h2>Message App:</h2>
<table class="table">
All,
Read,
Unread,
<thead>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th>Status</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in messages">
<td><input type="checkbox" v-model="selected" :value="item.id"></td>
<td>{{ item.status }}</td>
<td>{{ item.text }}</td>
</tr>
</tbody>

datatable only working for the first time

function SearchUser(url, pageIndex) {
var table;
table = $('#UsersTable').DataTable({
serverSide: true,
retrieve:true,
ajax: {
url: url,
type: "POST",
data: { username: $('#Username').val(), email: $('#Email').val(), companyID: $('#LifeCompanies').val(), page: pageIndex, isLocked: $('#Locked').is(':checked') }
},
columns: [
{ "data": "UserId" },
{ "data": "Username" },
{ "data": "Email" },
{ "data": "IsLockedOut" },
{
"render": function (data, type, full, meta) {
return '<span>wahoo</span>';
}
}
]
});
}
<div id="search">
<h3>Search:</h3>
#using (Html.BeginForm("Search","Admin"))
{
<div>
<table width="500px">
<thead>
<tr>
<td>Username:</td>
<td>#Html.TextBox("Username")</td>
</tr>
<tr>
<td>Email:</td>
<td>#Html.TextBox("Email")</td>
</tr>
<tr>
<td>Locked:</td>
<td>#Html.CheckBox("Locked")</td>
</tr>
<tr>
<td colspan="2">
<div id="searchForm">
#Html.Partial("SearchBuild")
</div>
</td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Search" onclick="SearchUser('/UserManagement/admin/Search',0)"/></td>
</tr>
</thead>
</table>
</div>
}
</div>
Hi the code above uses the datatables jquery plugin.
It seems to only work for the first time I use that function. The second time, it appears to hit the javascript but doesn't ever retrive any data from my mvc controller.
However if I use destroy instead of retrieve it works perfectly fine.
If I don't use retrieve or destroy, I get the "can't reinitialise table" error.
That function is just called by a button I click.
You need to modify your code to initialize your table and reload it separately.
Also it's not possible to modify initialization options via API unless you destroy and recreate the table.
You need another way to pass pageIndex variable. For example, you can create a hidden input with id PageIndex and set and retrieve value from there.
For example:
function initTable(url) {
var table;
table = $('#UsersTable').DataTable({
serverSide: true,
retrieve:true,
ajax: {
url: url,
type: "POST",
data: {
username: $('#Username').val(),
email: $('#Email').val(),
companyID: $('#LifeCompanies').val(),
page: $('#PageIndex').val(),
isLocked: $('#Locked').is(':checked')
}
},
columns: [
{ "data": "UserId" },
{ "data": "Username" },
{ "data": "Email" },
{ "data": "IsLockedOut" },
{
"render": function (data, type, full, meta) {
return '<span>wahoo</span>';
}
}
]
});
}
To search again you just need to call $('#UsersTable').DataTable().ajax.reload() API method.
If URL will change between searches use $('#UsersTable').DataTable().ajax.url(newurl).load() API method instead.