DataTables columns, columnDefs and rowCallback HTML5 initialisation - javascript

I currently have a datatable (ver 1.10.18) loaded with several options with js, but I need to make my code more reusable and I'm trying to initialise my datatable with html5 data-* attributes.
<table id="dataTable" cellspacing="0" width="100%" data-source="ajax.mysource.php">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th><i class="fas fa-low-vision"></i></th>
</tr>
</thead>
</table>
my jQuery code looks like:
var dataTable = $('#dataTable').DataTable({
processing: true,
serverSide: true,
ajax: $('#dataTable').data('source'),
columns: [
{ 'data': 'name' },
{ 'data': 'address' },
{ 'data': 'visible' }
],
order: [[ 1, 'asc' ], [ 0, 'asc' ]],
responsive: true,
nowrap: true,
pageLength: 15,
lengthChange: false,
select: 'single',
columnDefs: [
{ targets: 0, width: "110px" },
{ targets: 1, width: "150px" },
{ targets: 1, render: $.fn.dataTable.render.ellipsis(80) },
{ targets: 2, render: $.fn.dataTable.render.visibilityIcon() }
],
rowCallback: function(row, data, index) {
if (data.visible == "0") {
$(row).addClass("notVisible");
}
}
});
There are some options in common I would use for every datatable, but it would be great if I can set the columns, columnDefs and rowCallBack directly in my html using the html5 data-* attributes so I can use the same code for different tables, like:
<th data-columns="address" data-column-defs="{targets: 1, width:'150px'}" data-row-callback="function...">Address</th>
I haven't found anywhere how to use the html5-* attributes other than ordering, sorting and page length.
Is setting this options with html5 actually possible with datatables.js ?

First you need version 1.10.5 as stated here
As of v1.10.5 DataTables can also use initialisation options read from HTML5 data-* attributes
Then you have to put the data attributes to the table element and not to the column elements.
<table id="example"
data-column-defs='[{"targets": 0, "width": "200px"}]'
data-page-length='2'
data-class="dataTable"
data-order='[[ 1, "asc" ]]'
data-columns='[{"data": "name"}, {"data": "position"}]'
>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
<th>Start Date</th>
<th>office</th>
</tr>
</thead>
</table>
Here is the full snippet for you
var data = [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh"
},
{
"name": "Garrett Winters",
"position": "Director",
"salary": "$5,300",
"start_date": "2011/07/25",
"office": "Edinburgh"
},
{
"name": "Jane Doe",
"position": "SW Architect",
"salary": "$5,300",
"start_date": "2011/07/25",
"office": "Edinburgh"
},
{
"name": "John Doe",
"position": "SW Developer",
"salary": "$5,300",
"start_date": "2011/07/25",
"office": "Edinburgh"
}
];
var oTable = $('#example').dataTable({
data: data
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<table id="example"
data-column-defs='[{"targets": 0, "width": "200px"}]'
data-page-length='2'
data-class="dataTable"
data-order='[[ 1, "asc" ]]'
data-columns='[{"data": "name"}, {"data": "position"}]'
>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
<th>Start Date</th>
<th>office</th>
</tr>
</thead>
</table>

Related

DataTables can't get json

I use nodejs express and I want to show user data in my datatables
javascript datables
$(document).ready(function() {
$('#dataTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"datatype": "json",
"url": "/users",
"dataSrc": ""
},
"columns":
[
{ "data": "name" },
{ "data": "nickname" },
{ "data": "age" },
{ "data": "nicknames" }
]
})
})
json user data
{
name: "Apiphoom",
nickname: "Api",
age: "23",
test: "test"
}
html
<table class="table table-bordered" id="dataTable" >
<thead>
<tr>
<th>Name</th>
<th>Nickname</th>
<th>Age</th>
<th>Test</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
but it said "No matching records found",
How can I solve it.

ajax sourced datatable does not display any data and no error message is shown

the code for datatable call in jquery is as below
$(document).ready(function () {
$("#tableUserList").DataTable({
"ajax": {
"url": "AdminHome.aspx/getUsersForTable",
"dataType": "json",
"cache": false,
"contentType": "application/json; charset=utf-8",
"dataSrc": "d",
"type": "GET"
},
"columns": [
{"data": "d[id]"},
{"data": "d[username]"},
{"data": "d[user_type]"},
{"data": "d[first_name]"},
{"data": "d[last_name]"},
{"data": "d[address]"},
{"data": "d[email]"},
{"data": "d[phone_no]"},
]
});
});
When I checked the console no error is shown but neither is any data loaded into the datatable. My HTML table is as follows
<table id="tableUserList" class="table table-hover">
<thead>
<tr>
<th>UserID</th>
<th>Username</th>
<th>UserType</th>
<th>FirstName</th>
<th>LastName</th>
<th>Address</th>
<th>Email</th>
<th>Contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>UserId</td>
<td>Username</td>
<td>UserType</td>
<td>FirstName</td>
<td>LastName</td>
<td>Address</td>
<td>Email</td>
<td>Contact</td>
</tr>
</tbody>
</table>
and my ajax call returns data in this format.Showing a single row of returned data for simplicity
{
"d":[
{
"id":1,
"username":"admin",
"first_name":"admin",
"last_name":"admin",
"phone_no":"1234567210",
"address":"abc",
"email":"admin#gmail.com",
"user_type":"admin"
},
...
]
}
the data is returned properly means I am doing something wrong in binding the received data to the DataTable. Please suggest a solution.
I think your code will be fine if you fix what you are passing to "columns": [{"data": "d[id]"}, .... In the data property you would pass name of property from the data object so change it like "columns": [{"data": "id"}, ... and there you can also specify the title of this column when passing title property.
I give you a simple example with javascript source type of data, but it is analogical for the ajax sourced data.
$(document).ready(function () {
var data = {
"d":[
{
"id":1,
"username":"admin",
"first_name":"admin",
"last_name":"admin",
"phone_no":"1234567210",
"address":"abc",
"email":"admin#gmail.com",
"user_type":"admin"
},
{
"id":2,
"username":"user 1",
"first_name":"user",
"last_name":"first",
"phone_no":"1234567210",
"address":"address",
"email":"user#gmail.com",
"user_type":"user"
}
]
};
$("#tableUserList").DataTable({
"data": data.d,
"columns": [
{"data": "id", title: "ID"},
{"data": "username", title: "Username"},
{"data": "first_name", title: "First Name"},
{"data": "last_name", title: "Last Name"},
{"data": "phone_no", title: "Phone"},
{"data": "address", title: "Address"},
{"data": "email", title: "Email"},
{"data": "user_type", title: "Type"}
]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<table id="tableUserList" class="table table-hover">
</table>

Sending Json data as an object into DataTables

I have been trying to use DataTables. But after my Ajax request i get a Json object which i cannot pass into dataTables.
The Json object i receive is the following
{"data": [{"attributes": {"purchasedate": "04/01/2017", "medication": "meds", "cost": 100.0, "expirydate": "04/03/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Meds", "cost": 100.0, "expirydate": "04/02/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Super Meds", "cost": 267.0, "expirydate": "04/11/2017", "quantity": 250.0}, "type": "medical_inventory"}], "links": {"self": "/medical_inventory/"}}
Following is my HTML code
<table id="myTable" class="display" cellspacing="0" width="90%">
<thead>
<tr>
<th>Medication</th>
<th>Medication Quantity</th>
<th>Mediaction Cost</th>
<th>Purchase Date</th>
<th>Expiry Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Medication</th>
<th>Medication Quantity</th>
<th>Mediaction Cost</th>
<th>Purchase Date</th>
<th>Expiry Date</th>
</tr>
</tfoot>
</table>
The Ajax request i do is the following
$(document).ready(function () {
$.ajax({
url : '/api/medical_inventory/',
type : 'GET',
dataType : 'json',
success : function(data) {
assignToEventsColumns(data);
}
});
function assignToEventsColumns(data) {
var table = $('#myTable').dataTable({
"bAutoWidth" : false,
"aaData" : data,
"columns" : [ {
"data" : "medication"
}, {
"data" : "quantity"
}, {
"data" : "cost"
}, {
"data" : "purchasedate"
}, {
"data" : "expirydate"
} ]
})
}
});
This is the output i am currently getting
You were very nearly there:
function assignToEventsColumns(data) {
var table = $('#myTable').dataTable({
"bAutoWidth": false,
"aaData": data.data,
"columns": [{
"data": "attributes.medication"
}, {
"data": "attributes.quantity"
}, {
"data": "attributes.cost"
}, {
"data": "attributes.purchasedate"
}, {
"data": "attributes.expirydate"
}]
})
}
All you were missing was the structure of your JSON, you needed to add attributes. as well as your data.data :-D.Working JSFiddle here.
Try mapping the data to remove the attributes property of each object
success : function(data) {
data.data = data.data.map(function(item){
return item.attributes;
});
assignToEventsColumns(data);
}

populating jquery datatable ajax txt file

I'm a jquery/ajax newbie and going through data table examples. I'm having problems populating the data table with txt data in eclipse. I just get a loading message. Any assistance would be appreciated.
<table>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "data/object.txt",
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
</script>
/////object.txt
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},...................
In your code sample, you had the line,
"columns": [{ "data": "name" },{ "data": "position" },{ "data": "office" },{ "data": "extn" },{ "data": "start_date" },{ "data": "salary" }]
Simply change the columns to "columnDefs" which refers to the column defaults option in the datatable plugin.
And also, you are calling the data-table plugin on an id called "example" which you have not defined. So give your table an id="example"
So the final code should look like
$(document).ready(function() {
$('#example').dataTable({
"ajax": 'array.txt',
"columnDefs": [{ /* changed this */
"data": "name"
}, {
"data": "position"
}, {
"data": "office"
}, {
"data": "extn"
}, {
"data": "start_date"
}, {
"data": "salary"
}]
});
});
<link href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" 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>
</table>
Now this above code snippet WILL NOT work because the path to the array.txt is wrong. Copy the array.txt file locally. Fiddle or code snippet does not allow the ajax requests through them.
Here is the sample array.txt (copied from the data table website # https://www.datatables.net/examples/ajax/data/arrays.txt )
Hope this helps. Happy coding :)
Screenshot on my local machine

Table not being filled from Ajax Call using Datatables plug-in for jQuery

The ajax request is returning the following data
[{"ID":40,"Date":"\/Date(1407999600000)\/"},{"ID":39,"Date":"\/Date(1409036400000)\/"}
The HTML is:
<table id="bookings-table" class="display">
<thead>
<tr>
<th>ID</th>
<th>Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Date</th>
</tr>
</tfoot>
</table>
And the javascript is
$(document).ready(function () {
$('#bookings-table').dataTable({
"ajaxSource": "/manager/Booking/GetBookings",
"columns": [
{ "data": "ID" },
{ "data": "Date" }
]
});
});
Any idea why the table is not being filled
Just looking at their docs, I believe your json has to be formatted as so.
{
"data": [
{
"ID": 40,
"Date": "\/Date(1407999600000)\/"
},
{
"ID": 39,
"Date": "\/Date(1409036400000)\/"
}
]
}
Javascript error
$('#bookings-table').dataTable({
"ajax": {
"url": "/manager/Booking/GetBookings",
"dataSrc": ""
},
Sorted it all columns now bind

Categories