jquery Datatables add row. https://datatables.net - javascript

I am trying to ad a row to my java script data table (https://datatables.net)
ReportTable = $('#ReportsTable').dataTable({
//"data": Reportdata,
"bLengthChange": false,
"columns": [
{ "data": "name", "sTitle": "Name", "sWidth": "300px"},
{ "data": "type", "sTitle": "Report Type" },
{ "data": "timestamp", "sTitle": "Purchase Date" }
]
});
ReportTable.row.add("{name:'Test', type:'test', timestamp:'test'}").draw();
I have been following pages https://datatables.net/reference/api/rows.add() and http://www.datatables.net/examples/api/add_row.html with no luck.
The error i am getting reads as follows:
Uncaught TypeError: Cannot read property 'add' of undefined

ReportTable = $('#ReportsTable').dataTable(
must be
ReportTable = $('#ReportsTable').DataTable(

Why don't you try with:
ReportTable.row.add(['Test','test','test']).draw();
Because you added your columns name to your Datatable definition.

Swap out the DataTables include script with the following:
//cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js
I'm guessing you are using an outdated version that does not include the API you are trying to use.

You would have to rewrite to the following:
$('#ReportsTable').dataTable({
//"data": Reportdata,
"bLengthChange": false,
"columns": [
{ "data": "name", "sTitle": "Name", "sWidth": "300px"},
{ "data": "type", "sTitle": "Report Type" },
{ "data": "timestamp", "sTitle": "Purchase Date" }
]
});
var ReportTable = $('#ReportsTable').dataTable();
ReportTable.row.add("{name:'Test', type:'test', timestamp:'test'}").draw();

Related

jquery datatable binding data property to content that is displayed

I have my jQuery datatable plugin installed and I've initialized it like this:
$('#datatable-responsive2').DataTable({
// data: data,
// deferRender: true,
"pageLength": 25,
"bLengthChange": false,
"processing": true,
"serverSide": true,
"filter": false,
"orderMulti": false,
"ajax": {
"url": "/Administrator/LoadData/",
"type": "POST",
"datatype":"json"
},
"columns": [
{ "data": "FirstName", "name": "Lela", "autoWidth": true },
{ "data": "Email", "name": "Email", "autoWidth": true },
{ "data": "Active", "name": "Status", "autoWidth": true },
{ "targets": -1, "data": "UserId", "defaultContent": "<button>Click!</button>", "autoWidth": true },
{ "data": "FirstName", "name": "Full name", "autoWidth": true }
]
});
Please note this column:
{ "targets": -1, "data": "UserId", "defaultContent": "<button>Click!</button>", "autoWidth": true }
I've followed their documentation on how to render an HTML element there... But what I need now and wasn't able to figure how do I actually set a certain attribute for this HTML element inside the datatable when its being generated...
As u can see I've set data source for the datatable as UserId, and now I'd like each button "Click" to have value whatever the value of UserId is...
Can someone help me out?
P.S. so I want to output an HTML element in that column whos structure would be something like this:
<button values="whatever the value of userId is..?">Click me event</button>
You would need to define the render property of the column for that which would be the following :
{
"targets": -1,
"data": "UserId",
"render": function (data, type, full, meta) {
return "<button id='"+ data +"'>Click!</button>";
},
"autoWidth": true
}
The data property will be containing UserId in it which can be used in the render function.
You can refer to the documentation of it here

DataTable is not a function referenced files are loaded properly

I am using jquery datatables in a mvc. i have loaded the script files properly but still datables is not working.
Code in _layout.cshtml:
<!--Data table jquery-->
<script src="~/Content/jquery-2.2.3.js"></script>
<script src="~/Content/datatables/jquery.dataTables.js"></script>
and code in index.cshtml for datatable:
$(document).ready(function () {
//jQuery DataTables initialization
var table = $('#MyTable').DataTable({
"processing": true, // for show processing bar
"serverSide": true, // for process on server side
"orderMulti": false, // for disable multi column order
"dom": '<"top"ip>rt<"bottom"lp><"clear">', // for hide default global search box // little confusion? don't worry I explained in the tutorial website
"ajax": {
"url": "/Product/LoadData",
"type": "POST",
"datatype": "json"
},
"aoColumns": [
{ "mData": "ProductID", "name": "ProductID", "visible": false, "autoWidth": true },
{ "mData": "ProductName", "name": "ProductName", "visible": false, "autoWidth": true },
{ "mData": "Qty", "name": "Qty", "autoWidth": true },
{ "mData": "UnitPrice", "name": "UnitPrice", "visible": true, "autoWidth": true },
{ "mData": "CatagoryID", "name": "CatagoryID", "autoWidth": false },
{ "mData": "catagoryname", "name": "catagoryname", "visible": true, "autoWidth": true }
]
});//End DataTable
});
When i run it gives following error:
Uncaught TypeError: $(...).DataTable is not a function
(anonymous function)# Product:91
fire # jquery-2.2.3.js:3187
fireWith # jquery-2.2.3.js:3317
ready # jquery-2.2.3.js:3536
completed # jquery-2.2.3.js:3552
you have your datatable.js in your _layout , you could be creating a conflict , set your datatable.js benchmark index at the end along with your declaration of datatable for all the DOM is preloaded when running the $().datatable

Datatables initialization warning

I have a dropdown with multiple options that initializes a datatable using javascript. Everything works fine but the problem comes during execution in which when the option is selected second time i get an error , check out this fiddle,
DataTables warning (table id = 'defDiv'): Cannot reinitialise DataTable.
And Below is my code :
if(user.position=="DEF"){
var table = $('#defDiv').DataTable({
"aaData":defenders,
"iDisplayLength":15,
"aoColumns": [
{ "mDataProp": "playerInfo" },
{ "mDataProp": "playerName" },
{ "mDataProp": "playerClub" },
{ "mDataProp": "playerValue" },
{ "mDataProp": "playerPoints" },
],
"order": [[ 3, "desc" ]],
});
}
Question is how can i prevent the warning from happening when the option is selected again ?
I've altered you code and it works now:
var goalkepeers = [{
"playerName": "Mignolet",
"playerClub": "Liverpool",
"playerValue": "5.0",
"playerPoints": "89",
}, {
"playerName": "de Gea",
"playerClub": "Manchester",
"playerValue": "6.7",
"playerPoints": "120",
}];
var defenders = [{
"playerName": "Ivanovic",
"playerClub": "Chelsea",
"playerValue": "7.8",
"playerPoints": "100",
}, {
"playerName": "Mertesacker",
"playerClub": "Arsenal",
"playerValue": "7.7",
"playerPoints": "110",
}];
var aoColumns = [{
"sTitle": "Name",
"mDataProp": "playerName"
},{
"sTitle": "Club",
"mDataProp": "playerClub"
},{
"sTitle": "Value",
"mDataProp": "playerValue"
},{
"sTitle": "Points",
"mDataProp": "playerPoints"
}];
var table = null;
$("#playersFilter").change(function () {
var value = $('#playersFilter').val();
if (value == "gk") {
if ($.fn.dataTable.isDataTable('#players')) {
$('#players').DataTable().destroy();
}
table = $('#players').DataTable({
"aaData": goalkepeers,
"iDisplayLength": 15,
"aoColumns": aoColumns,
"bRetrieve": true,
"order": [
[3, "desc"]
],
"bDestroy": true
});
} else if (value == "def") {
if ($.fn.dataTable.isDataTable('#players')) {
$('#players').DataTable().destroy();
}
table = $('#players').DataTable({
"aaData": defenders,
"iDisplayLength": 15,
"aoColumns": aoColumns,
"bRetrieve": true,
"order": [
[3, "desc"]
],
"bDestroy": true,
});
}
});
I'm pretty sure there's a more efficient way of doing it, I'll have a think and post a link to a JSFiddle as a comment.
You only really need the one table as well:
<select id="playersFilter">
<option>Choose Players</option>
<option value="gk">goalkepeers</option>
<option value="def">Defenders</option>
</select>
<table class="display" id="players"></table>
use this code
if(user.position=="DEF"){
var table = $('#defDiv').DataTable({
"aaData":defenders,
"iDisplayLength":15,
"aoColumns": [
{ "mDataProp": "playerInfo" },
{ "mDataProp": "playerName" },
{ "mDataProp": "playerClub" },
{ "mDataProp": "playerValue" },
{ "mDataProp": "playerPoints" },
],
//EDITS
"bRetrieve":true,
"order": [[ 3, "desc" ]],
// use this in your code
"bDestroy": true,
});
}
this will work for me &
more details
Can you just destroy the table prior to re-initialization?
table.DataTable().destroy();
Something like this:
var table;
if ($.fn.dataTable.isDataTable('#defDiv')) {
table.DataTable().destroy();
}
table = $('#defDiv').DataTable({...
Documentation can be found here
Demo here

Binding datatable with to JSON array from autocomplete

I am using an autocomplete field to get data from a server and display that in a datatable:
$("#firstname").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://myhost.com/webservices/test3.cfm",
data: request,
success: function (data) {
$('#results').dataTable({
"bProcessing": true,
"bJQueryUI": true,
"bLengthChange": true,
"bFilter": true,
"bAutoWidth": false,
"bRetrieve" : true,
"aaData": data ,
"aoColumns": [
{ "sTitle": "Name", "sName": "name" },
{ "sTitle": "Title", "sName": "title" },
{ "sTitle": "Organization", "sName": "organization" },
{ "sTitle": "Email", "sName": "email" },
{ "sTitle": "Status", "sName": "status" }
]
});
}
});
}
The data return from the ajax call is:
[["Steven, Grek", "President", "Sands Corp.", "steven#yahoo.com", "1"],["Steven, Grek", "Associate", "Alliance Ltd.", "steven#yahoo.com", "1"],["Steven, Grek", "President", "Forest Products Association", "steven#yahoo.com", "1"]]
I get the following errors:
DataTables warning (table id = 'results'): Requested unknown parameter '1' from the data source for row 0
DataTables warning (table id = 'results'): Requested unknown parameter '1' from the data source for row 9
Showing 1 to 10 of 2,147 entries
If I replace "aaData": data
with the response from in the data:
"aaData": [["Steven, Grek", "President", "Sands Corp.", "steven#yahoo.com", "1"],["Steven, Grek", "Associate", "Alliance Ltd.", "steven#yahoo.com", "1"],["Steven, Grek", "President", "Forest Products Association", "steven#yahoo.com", "1"]]
it works.
Any idea what I am doing wrong?
Figured it out with the help of a co-worker:
The typeof data coming from my ajax call is a string.
$("#firstname").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://myhost.com/webservices/test3.cfm",
data: request,
success: function (data) {
var obj = jQuery.parseJSON(data); <---- typeof data is a string
$('#results').dataTable({
"bProcessing": true,
"bJQueryUI": true,
"bLengthChange": true,
"bFilter": true,
"bAutoWidth": false,
"bRetrieve" : true,
"aaData": obj, <---- Use the parsed json object instead
"aoColumns": [
{ "sTitle": "Name", "sName": "name" },
{ "sTitle": "Title", "sName": "title" },
{ "sTitle": "Organization", "sName": "organization" },
{ "sTitle": "Email", "sName": "email" },
{ "sTitle": "Status", "sName": "status" }
]
});
}
});
},
});

DataTables: search all columns when server-side

I'm using IgnitedDatatables (CodeIgniter library) for DataTables. The table gets generated without problems but if I search/filter it can only filter one column at a time. If I set "bServerSide" to false it works but then I lose the server-side functionality.
In the examples, this one is working:
http://datatables.net/release-datatables/examples/ajax/custom_data_property.html
while this isn't (server-side):
http://datatables.net/release-datatables/examples/data_sources/server_side.html
Is this not possible to achieve when running server-side?
This is my JSON response (shortened and with replaced data):
{"sEcho":0,"iTotalRecords":45438,"iTotalDisplayRecords":45438,"aaData":[["abc","12345","example#example.com","","","2010-01-27 22:31:10","Edit<\/a> Delete<\/a>"],["abc2"," test123","test#test.com","","","2008-06-15 22:09:33","Edit<\/a> Delete<\/a>"]],"sColumns":"fname,lname,email,phone,cellphone,created,edit"}
JavaScript code:
$("#members").dataTable( {
"bProcessing": true,
"bServerSide": true,
'sAjaxSource': '<?php echo base_url();?>members/listener',
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": 'POST',
"url": sSource,
"data": aoData,
"success": fnCallback
} );
},
"bLengthChange": false,
"aaSorting": [[ 0, "asc" ]],
"iDisplayLength": 15,
"sPaginationType": "full_numbers",
"bAutoWidth": false,
"aoColumnDefs": [
{ "sName": "fname", "aTargets": [ 0 ] },
{ "sName": "lname", "aTargets": [ 1 ] },
{ "sName": "email", "aTargets": [ 2 ] },
{ "sName": "phone", "sWidth": "80px", "aTargets": [ 3 ] },
{ "sName": "cellphone", "sWidth": "100px", "aTargets": [ 4 ] },
{ "sName": "created", "sWidth": "120px", "aTargets": [ 5 ] },
{ "bSortable": false, "sName": "edit", "sWidth": "115px", "aTargets": [ 6 ] }
]
});
Thank you!
Well, the problem if you filter server side is that you are filtering through an SQL query and this is what is written on the example you posted;
Filtering
NOTE this does not match the built-in DataTables filtering which does it
word by word on any field. It's possible to do here, but concerned about efficiency
on very large tables, and MySQL's regex functionality is very limited
Basically you could do what you want to do (a regular expression match an all columns) but it's going to kill the performance server side.
What i usually do is provide a filter for each column, i need to filter.

Categories

Resources