DataTables can't get json - javascript

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.

Related

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>

DataTable generating unwanted extra columns

I am trying to pouplate datatable with data from the server but its generating non existent td which I have not defined.
Javascript
$('.datatable-basic').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": base_url + 'leave/DraftJSON/'
},
"columns": [
{ "data": "name" },
{ "data": "sd" },
{ "data": "end" },
{ "data": "id"}
]
});
HTML:
<table class="table datatable-basic" >
<thead>
<tr>
<th>Leave</th>
<th>Start</th>
<th>End</th>
<th class="text-center" col="2">Actions</th>
</tr>
</thead>
</table>
Ajax Request Response:
{"data":[{"id":"2","uid":"2","lid":"2","sd":"21 June, 2017","stod":"Afternoon","end":"21 June, 2017"
,"etod":"Afternoon","reason":"ddada","rid":"1","draft":"0","name":"Compassionate","person":"Ms. Ochieng
, Alphonc O"},{"id":"3","uid":"1","lid":"4","sd":"2017\/06\/20","stod":"Morning","end":"2017\/06\/22"
,"etod":"Afternoon","reason":"qeqeqeq","rid":"1","draft":"0","name":"Paternity","person":"Ms. Ochieng
, Alphonc O"}]}
HTML generated by DataTable:
<tbody>
<tr class="odd" role="row">
<td class="sorting_1">Compassionate</td>
<td>21 June, 2017</td>
<td>21 June, 2017</td>
<td>2</td>
<td></td> //non-existent
<td></td> //non-existent
</tr>
<tr class="even" role="row">
<td class="sorting_1">Paternity</td>
<td>2017/06/20</td>
<td>2017/06/22</td>
<td>3</td>
<td></td> //non-existent
<td></td> //non-existent
</tr>
</tbody>
The commented tds are extra sadded by datatable which then produces an error. Any insights?
It works here as you wish.
When I tried to beautify your json file json formatter gived me an error in person property. I removed invalid character in person property and prepared plunker with your json data.
{
"data":
[
{
"id":"2",
"uid":"2",
"lid":"2",
"sd":"21 June, 2017",
"stod":"Afternoon",
"end":"21 June, 2017",
"etod":"Afternoon",
"reason":"ddada",
"rid":"1",
"draft":"0",
"name":"Compassionate",
"person":"Ms. Ochieng, Alphonc O"
},
{
"id":"3",
"uid":"1",
"lid":"4",
"sd":"2017\/06\/20",
"stod":"Morning",
"end":"2017\/06\/22",
"etod":"Afternoon",
"reason":"qeqeqeq",
"rid":"1",
"draft":"0",
"name":"Paternity",
"person":"Ms. Ochieng, Alphonc O"
}
]
}
//jquery
$('.datatable-basic').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": 'data.json'
},
"columns": [
{ "data": "name" },
{ "data": "sd" },
{ "data": "end" },
{ "data": "id"}
]
});

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

new columns not showing on datatables js

i'm trying to add new columns to the datatables but they are not showing
i add the header of both of them.
Here's the html part:
<div class="table-responsive">
<table class="display dataTables table-bordered" cellspacing="0" id="userteams_table">
<thead class="thead">
<tr>
<th class="text-center">
Team Name
</th>
<th class="text-center">
Team Country
</th>
<th class="text-center">
Fan Type
</th>
<th class="text-center">
Global Rating
</th>
<th class="text-center">
Local Rating
</th>
<th class="text-center">
Remove
</th>
</tr>
</thead>
</table>
Here's the datatable columns part in js:
"columns": [
{ "data": "Name" },
{ "data": "Country" },
{ "data": "FanType" },
{ "data": "GlobalRating" },
{ "data": "LocalRating" },
{ "data": "TeamID" }
I also attach an image of the outcome:
[![enter image description here][1]][1]
the server side fills all fields.
Thank you for your help
UPDATE
I added the full datatable use in js
function loadUserTeamsTable(data) {
dt2 = $('#userteams_table').DataTable({
"order": [[0, "desc"]],
"bStateSave": true,
"fnStateSaveParams": function (oSettings, sValue) {
/* $.cookie("Status", $("#Status").val(), { expires: 7 });
$.cookie("TemplateID", $("#TemplateID").val().replace('-', ''), { expires: 7 });
$.cookie("FamilyID", $("#FamilyID").val(), { expires: 7 });
$.cookie("LastTreatmentByID", $("#LastTreatmentByID").val(), { expires: 7 });*/
},
"fnStateLoadParams": function (oSettings, oData) {
/*$("#Status").val($.cookie("Status"));
$("#TemplateID").val($.cookie("TemplateID"));
$("#FamilyID").val($.cookie("FamilyID"));
$("#LastTreatmentByID").val($.cookie("LastTreatmentByID"));*/
},
"sDom": 'T<"clear">lfrtip',
"oTableTools": {
"sSwfPath": "/Scripts/DataTables-1.10.4/extensions/TableTools/swf/copy_csv_xls.swf",
"aButtons": []
},
"pagingType": "full_numbers",
"language": {
"sProcessing": "Processing...",
"sLengthMenu": "show _MENU_ items",
"sZeroRecords": "No Match were found",
"sInfo": "_START_ To _END_ From _TOTAL_ Teams",
"sInfoEmpty": "0 To 0 From 0 Teams",
"sInfoFiltered": "(מסונן מסך _MAX_ רשומות)",
"sInfoPostFix": "",
"sSearch": "Team Free Search:",
"sUrl": "",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
}
},
"serverSide": true,
"orderMulti": false,
"ajax": {
"url": "/Users/FilterUserTeamsData",
"data": function (d) {
d.jsona = JSON.stringify(new JsonUserTeamSearch());
d.freeText = $("#userteams_table_filter input").val();
},
"type": "POST",
"dataType": "json",
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.responseText);
}
},
//"aaData": data,
"columns": [
{ "data": "Name" },
{ "data": "Country" },
{ "data": "FanType" },
{ "data": "GlobalRating" },
{ "data": "LocalRating" },
{ "data": "TeamID" }
],
"columnDefs": [
{ "width": "10%", "targets": [0, 1, 2, 3, 4, 5] },
{ "type": "date", "targets": [1] }
],
"fnInitComplete": function () {
$($('.panel')[1]).append($('.DTTT_container'));
}
});
}
if the datatables not showing any columns check the following:
1. add headers in the table
2. check for typos between the data from the server and what each column bind to
3. force refresh of the browser (ctrl F5)

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