populating jquery datatable ajax txt file - javascript

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

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.

DataTables columns, columnDefs and rowCallback HTML5 initialisation

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>

Add edit/delete icon to row of data populated by JSOn (AjaxCall)

I have an HTML table which is being populated by a JSON (ajax call). In the Edit and Delete columns of the table I need to have an icon to edit or delete the data on each row.
I don't know how to add the icon when the table is populated by the JSON.
Following is my code:
//JSON which is populating the table. Register.js
$(document).ready(function() {
var allRegister = AjaxCall(apiUrl, mthdGetReleasesFullList, null,
{
});
var data=allRegister.responseText;
alert("testing"+ data);
var jsonResponse = JSON.parse(data);
//var table = $('#contact-data').DataTable({
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
],
"order": [[1, 'dsc']]
});
});
Html code for table:
<link rel="stylesheet" href="entity/Register/css/Register.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Page specific JS -->
<script src="entity/Register/js/Register.js"></script>
<div class="container-full">
<div class="heading-1">
<input type="button" id="btn-AddUser" value="Add Release" style="font-size:14px;color:teal;text-align: left">
<h1>
</h1>
<div class="modular-box-text inset">
<div class="retgister-table-holder">
<h2>Pre-Release Access Register:</h2>
<br>
<div class="register-table" >
<table id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusIDth>
<th>Edit<th>
<th>Delete </th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
You need to work with the render option of the columns objects - documentation here. When you specify the targeted ID of your desired action (i presume it is ReleaseID) you just create more columns with that ID as data object and adjust the column renderer by giving it a custom render method. Since you specified ReleaseID as data, you can re-use that value in the render method as first argument.
In the example below you can see how to achieve this - You can very easily replace Edit and Delete text with <img /> tags referencing the icons you want to have for each action.
// Faking a request
var response = [
{ "ReleaseID": "1",
"ReleaseName": "Release A",
"DivisionID": "10",
"StatusID": "1"
}, {
"ReleaseID": "2",
"ReleaseName": "Release B",
"DivisionID": "9",
"StatusID": "2"
}, {
"ReleaseID": "3",
"ReleaseName": "Release C",
"DivisionID": "9",
"StatusID": "1"
}, {
"ReleaseID": "4",
"ReleaseName": "Release D",
"DivisionID": "10",
"StatusID": "2"
}, {
"ReleaseID": "5",
"ReleaseName": "Release E",
"DivisionID": "11",
"StatusID": "1"
}];
$(document).on('ready', function() {
$('#register-data').dataTable({
"data": response,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{
"data": "ReleaseID",
"render": (data, type, row, meta) => `Edit`
}, {
"data": "ReleaseID",
"render": (data, type, row, meta) => `Delete`
}
],
"order": [[1, 'dsc']]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/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 id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusID</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Thanks for your response.
I used the following to get Edit and Delete buttons to appear on all rows of table
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{"data":null, "defaultContent": "<button class='btn-Edit'>Edit</button>"},
{"data":null, "defaultContent": "<button class='btn-Delete'>Click!</button>"},
],
"order": [[1, 'dsc']]
});

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);
}

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