Datatables not populating with data from RestAPI call - javascript

when trying to read back my api into data tables im getting an error "Cannot read property 'length' of undefined"
my table is as follows:
<div class="container-fluid d-flex flex-column min-vh-100 justify-content-center align-items-center">
<div class=" row d-flex justify-content-center ">
<!-- Table -->
<table id="movieTable" class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Year</th>
</tr>
</thead>
<tbody id="list-list">
</tbody>
</table>
</div>
</div>
And my script is as follows:
<script>
$('#movieTable').DataTable({
"ajax": "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id=1",
dataSrc: "",
"columns": [
{
"data": "Title"
}, {
"data": "Year"
},
]
});
</script>
I can't see exactly what I'm doing wrong, any help appreciated!
Edit, after the advice given I've edit my script to be the following:
<script>
$('#movieTable').dataTable({
ajax: {
url: "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id=2",
dataSrc: "tv_shows",
"columns": [
{
"Title": "Title"
}, {
"Year": "Year"
},
]
},
});
</script>
My JSON response is as follows:
{
"status": "true",
"message": "Customer Details",
"tv_shows": {
"id": "456",
"Title": "Vampire Knight",
"Year": "2008",
"Age": "16+",
"IMDb": "7.5",
"RottenTomatoes": "",
"Netflix": "1",
"Hulu": "1",
"Prime": "0",
"Disney": "0"
}
}
I think my api might be the problem, i've set it to return values based on the ID queried. if i don't add ?id='x' my response is as follows:
{
"status": "false",
"message": "No customer(s) found!"
}
The code used to build my api is:
//return JSON by id
if (isset($_GET['id']) && $_GET['id']!="") {
$id = $_GET['id'];
$query = "SELECT * FROM tv_shows WHERE id={$id}";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$tableData['id'] = $row['id'];
$tableData['Title'] = $row['Title'];
$tableData['Year'] = $row['Year'];
$tableData['Age'] = $row['Age'];
$tableData['IMDb'] = $row['IMDb'];
$tableData['RottenTomatoes'] = $row['RottenTomatoes'];
$tableData['Netflix'] = $row['Netflix'];
$tableData['Hulu'] = $row['Hulu'];
$tableData['Prime'] = $row['Prime'];
$tableData['Disney'] = $row['Disney'];
$response["status"] = "true";
$response["message"] = "Customer Details";
$response["tv_shows"] = $tableData;
} else {
$response["status"] = "false";
$response["message"] = "No customer(s) found!";
}
echo json_encode($response); exit;
Updated api code to return a collection of objects rather than just one
JSon resposne as follows:
{
"data": [
{
"Title": "Breaking Bad",
"Year": "2008",
"Age": "18+",
"IMDb": "9.5",
"Rotten Tomatoes": "96%",
"Netflix": "1",
"Prime": "0",
"Hulu": "0",
"Disney": "0"
},
{
"Title": "Stranger Things",
"Year": "2016",
"Age": "16+",
"IMDb": "8.8",
"Rotten Tomatoes": "93%",
"Netflix": "1",
"Prime": "0",
"Hulu": "0",
"Disney": "0"
},
Datatables script is:
<script>
$('#movieTable').DataTable({
"processing": true,
"serverSide": true,
"sPaginationType": "full_numbers",
"order": [],
"ajax": {
"url": "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi2.php",
"type": 'get',
"dataType": 'json'
},
"columns": [
{ "data": "Title" },
{ "data": "Year" },
]
});
</script>
Still no data in the datatables!

Got it working thanks to #andrewjames for his help!
I had to change my api to output an array of objects rather than one object and ensure JSON output matched the output defined in datatables documentation.
Working JS code:
<script>
$(document).ready(function() {
$('#movieTable').DataTable( {
"ajax": {
"url": "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi2.php",
"dataSrc": "data"
},
"columns": [
{ "data": "id" },
{ "data": "Title" },
{ "data": "Year" },
{ "data": "Age" },
{ "data": "IMDb" },
{ "data": "Rotten Tomatoes" },
]
} );
} );
</script>
HTML table structure:
<div class="container-fluid d-flex flex-column min-vh-100 justify-content-center align-items-center">
<div class=" row d-flex justify-content-center ">
<!-- Table -->
<table id="movieTable" class="display" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Title</th>
<th>Year</th>
<th>Age</th>
<th>IMDb</th>
<th>Rotten Tomatoes</th>
</tr>
</thead>
</table>
</div>
</div>

Related

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

Import JSON to html (table) filtering results

I'm trying to import JSON data to a html table. I have different types of data. In my case I need only to see the "link" data type in a table this is the JSON data I'm getting.
{ "data": [
{
"type": "photo",
"created_time": "2017-11-15T14:30:43+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/693061044378702",
"shares": {
"count": 2270
},
"id": "104957429855736_693061044378702"
},
{
"type": "link",
"created_time": "2017-11-15T02:34:46+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/692656794419127",
"shares": {
"count": 86
},
"id": "104957429855736_692656794419127"
},
{
"type": "photo",
"created_time": "2017-11-15T00:34:50+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/692493157768824",
"shares": {
"count": 1628
},
"id": "104957429855736_692493157768824"
},
{
"type": "photo",
"created_time": "2017-11-14T23:51:53+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/692442954440511",
"shares": {
"count": 6239
},
"id": "104957429855736_692442954440511"
This is the code I have:
<body>
<input type="text" class="txtPagina">
<button class="btnBuscar">Buscar</button>
<table class="tabla" border='1'>
<tr>
<td>Type</td>
<td>created time</td>
<td>permalink url</td>
<td>Shares Count</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btnBuscar').on('click', function (){
var pagina = $('.txtPagina').val();
//Ajax
$.ajax({
type: "GET",
dataType: "json",
url: "https://graph.facebook.com/"+pagina+"/feed?fields=type,created_time,permalink_url,shares&limit=25& access_token=(mytoken)",
success: function(data){
$.each(data.data, function(i, d){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.type+'</td><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td>'+s+'</tr>');
});
},
error: function (){
console.log("Error");
And this is the result I'm getting:
As you can see I'm getting photos and links but I need to see only links.
Just add an if statement in your loop to filter out the photos.
$.each(data.data, function(i, d){
if(d.type =='link'){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.type+'</td><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td>'+s+'</tr>');
}
});
in your each loop:
if(d.type == 'link') {
//Add as you already do
}
Done!

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)

Could not load Datatable with JSON objects

I am trying for pagination from dynamic data. I started using Datatable but I am not able to load Datatable with JSON Objects.
Please find my code below:
function drawTable(data) {
$('#t01').DataTable( {
ajax: {
"aaData": data,
"dataSrc": ""
},
"aoColumns": [
{ "mdata": "UserName" },
{ "mdata": "AppName" },
{ "mdata": "OS" },
{ "mdata": "Changes" },
{ "mdata": "Time" }
]
} );
}
My JSON:
[{
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : true to false, ",
"Time": "2016-03-22 11:36:09"
}, {
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : false to true, ",
"Time": "2016-03-22 11:44:11"
},..
My html page:
<table id="t01" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>UserName</th>
<th>AppName</th>
<th>OS</th>
<th>Changes</th>
<th>Time</th>
</tr>
</thead>
</table>
The table is not getting loaded but loading ... appears in table. I have checked, JSON is in correct format.
I edited my code:
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"processing" : true,
"data": data,
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}
and now my table is loaded with blank columns and I am getting error as:
DataTables warning: table id=t01 - Requested unknown parameter 'UserName' for row 0, column 0.
Your code work fine for me. This is how I used it :
first : I create a json.php who contains the following code :
[{
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : true to false, ",
"Time": "2016-03-22 11:36:09"
}, {
"UserName": "testUser",
"AppName": "mtv_app",
"OS": "android",
"Changes": "tveEnabled : false to true, ",
"Time": "2016-03-22 11:44:11"
}]
After I create an other page test.php with these following codes :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="https://www.datatables.net/release-datatables/extensions/TableTools/css/dataTables.tableTools.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="t01" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>UserName</th>
<th>AppName</th>
<th>OS</th>
<th>Changes</th>
<th>Time</th>
</tr>
</thead>
</table>
</body>
<script type="text/javascript">
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"processing" : true,
"data": data,
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}
$(document).ready(function() {
$.ajax({
url: "json.php",
dataType: "json",
success: function(data) {
drawTable(data);
}
});
});
</script>
</html>
And this is the result :
try this, i think this useful
function drawTable(data) {
console.log(data);
$('#t01').DataTable( {
"bProcessing": true,
"bServerSide": true,
"bFilter" : false,
"sAjaxSource": "data.php",//your data source
"columns": [
{ "data": "UserName" },
{ "data": "AppName" },
{ "data": "OS" },
{ "data": "Changes" },
{ "data": "Time" }
]
} );
}

Categories