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" }
]
} );
}
Related
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>
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!
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);
}
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)
I would like to output a bootstrap label for one value of a field in a JQuery dataTable. This fields possible values can be '0' or '1' and depending on the result I want to decide which bootstrap label I want to output in the dataTable. Unfortunately I don't know how I can do this if statement for this case.
My JQuery:
$(document).ready(function() {
$('#accountOverview').dataTable( {
"ajax": {
"url": "/database/accounts.php",
"data": {"action": "selectAccounts"},
"dataSrc": ""
},
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
{ "data": "profitDay" },
{ "data": "playerName" },
{ "data": "tradepileCards" },
{ "data": "tradepileValue" },
{ "data": "enabled" }
],
"autoWidth": false
});
});
I need to use something like this for the result of the "enabled" field:
if(enabled==1) <label class="label label-success">Online</label>
else <label class="label label-error">Offline</label>
HTML Table:
<table id="accountOverview" class="table datatable">
<thead>
<tr>
<th>E-Mail</th>
<th>Platform</th>
<th>Coins</th>
<th>Profit last 24h</th>
<th>Playername</th>
<th>Tradepile Cards</th>
<th>Tradepile Value</th>
<th>Status</th>
</tr>
</thead>
<tbody id="accountList">
<!-- List all accounts -->
</tbody>
</table>
The label needs to be in the field "status" = the last each row.
Following dataTable's "draw" (which happens after AJAX loads your data), you can look up the last td of each row and use wrapInner() to inject the HTML you want. So, in your case, try:
var apply_label=function(){
$('#accountOverview').find('td:last-child').not(':has(.label)').each(function(){
if( this.innerHTML==="1"){
$(this).wrapInner('<span class="label label-success"></span>');
}
else {
$(this).wrapInner('<span class="label label-danger"></span>');
}
});
};
$('#accountOverview').dataTable( {
"ajax": {
"url": "/database/accounts.php",
"data": {"action": "selectAccounts"},
"dataSrc": ""
},
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
{ "data": "profitDay" },
{ "data": "playerName" },
{ "data": "tradepileCards" },
{ "data": "tradepileValue" },
{ "data": "enabled" }
],
"autoWidth": false,
"drawCallback": function( settings ) {
apply_label();
}
});
Notes:
I think you want span (not label).
I think you want .label-danger (not .label-error).
Check it out at http://jsfiddle.net/jhfrench/wrkkbcf1/.