This is my first attempt at jQuery datatables.
I am trying to populate html table with data from php using jquery datatables.
The code below is stuck on Loading data from server.
Any ideas what changes I need to make to make this work?
<link rel="stylesheet" type="text/css" href="css/header.css">
<div id="container">
<div style="width:680px">
<table id="tbDetails" cellpadding="0" cellspacing="0" id="example">
<thead style="background-color:#DC5807; color:White; font-weight:bold;font-size:10pt;">
<tr style="border:solid 1px #000000">
<th width="5%">ID</th>
<th width="10%">Date</th>
<th width="10%">Request Status</th>
<th width="15%">Requestor FullName</th>
<th width="15%">Requestor WorkPhone</th>
<th width="15%">Requestor Email</th>
<th width="15%">Primary SiteContact</th>
<th width="15%">Secondary SiteContact</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="8" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</div>
<div class="spacer"></div>
</div>
<style type="text/css">
#import "jquery/dataTables/media/css/jquery-ui.css";
#import "jquery/datatables/media/css/demo_table.css";
td{padding-right:30px;}
.row_selected{color: gray;}
</style>
<script type="text/javascript">
$(document).ready(function() {
var what = "customer";
/* Init DataTables */
var oTable = $('#example).dataTable({
"bJQueryUI" : true,
//"bProcessing" : true,
"bServerSide" : true,
"sPaginationType" : "RequestID",
"sAjaxSource" : "filltable.php",
"aoColumns" : [{
"sClass" : "center",
"bSortable" : false,
}, {
"sName" : "RequestID",
"mData" : "2"
}, {
"sName" : "RequestDate",
"mData" : "3"
}, {
"sName" : "RequestStatus",
"mData" : "4"
}, {
"sName" : "RequestorFullName",
"mData" : "5"
}, {
"sName" : "RequestorWorkPhone",
"mData" : "6"
}, {
"sName" : "RequestorEmail",
"mData" : "7"
}, {
"sName" : "PrimarySiteContactDisplay",
"mData" : "8"
}, {
"sName" : "SecondarySiteContactDisplay",
"mData" : "9"
}],
"aaSorting" : [[1, 'RequestDescription']]
})
});
</script>
Many thanks in advance
For some reason, maybe my browser is old, it is no longer allowing me to click on Add commnt.
Iny anycase, thanks for pointing that out. I don't know why it disappeared after my post.
My code has tick marks.
Needless to say, that's not the problem.
Eduardo, please forgive me. for some reason, just today, this is not allowing me to Add comments.
so, I am doing it here.Naybe old browser.
I think the way I am doing it should work though.
So, I am really not sure what the problem is.
I will attempt to change to your suggestion but not sure that's the solution here.
You're missing a closing quote in this line -
var oTable = $('#example).dataTable({
It should be -
var oTable = $('#example').dataTable({
You need to return the response of the server on a specific format, also if the quote is missing like #Jay Blanchard say it won't work. but if it was a typo maybe the response that you're sending back from your php script
"sAjaxSource" : "filltable.php"
Is not correct, look at the documentation
Server side processing Datatables
Also in the aaSoring you need to specify the column index and then the desired order
[[1, 'desc']]
[[1, 'asc']]
I did't realized that you're using mData to map your columns to the JSON properties my bad, if you are trying to make your columns match your index of the data on the JSON object your need to set an integer otherwise it will try to look for something like this
{"2":"Your val"}
Setting mData with an integer will look for the index, maybe that's why it is stopping on the loading data from server step.
http://datatables.net/ref#mData
Related
On the list page user can edit info by click on Edit button and open details page for edit data.
After edit done return list page. This my source code
My JS listUser.js is embbed in jsp file at the bottom listusers.jsp
<div class="c-body">
<main class="c-main">
<div class="container-fluid">
<div class="fade-in" id="content">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-sm-4">List Users</div>
<div class="col-sm-8 text-right">
<button id="create_user" type="button" class="btn btn-primary">Tạo mới</button>
</div>
</div>
</div>
<div class="card-body">
<table id="userTable" class="table table-striped table-bordered datatable">
<thead>
<tr>
<th>Username</th>
<th>Full Name</th>
<th>Site</th>
<th>Roles</th>
<th>Areas</th>
<th>Team</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="${contextPath}/user/listUser.js"></script>
</div>
</div>
</main>
</div>
listUser.js
$( document ).ready(function() {
var userTable = $('#userTable').DataTable( {
"processing": true,
"serverSide": true,
"pageLength": 10,
"ajax": {
"url": "/user/paginated",
"data": function ( data ) {
}},
"columns": [
{ "data": "username", "name" : "Username", "title" : "Username", "defaultContent" : ""},
{ "data": "full_name", "name" : "Full Name" , "title" : "Full Name", "defaultContent" : ""},
{ "data": "site_code", "name" : "Site" , "title" : "Site", "defaultContent" : ""},
{ "data": "user_roles", "name" : "Roles", "title" : "Roles", "defaultContent" : ""},
{ "data": "user_areas", "name" : "Areas", "title" : "Areas", "defaultContent" : ""},
{ "data": "team_code", "name" : "Team", "title" : "Team", "defaultContent" : ""},
{ "data": "status", "name" : "Status", "title" : "Status", "defaultContent" : ""},
{ "targets": "no-sort", "orderable": false, "data": "null", "name" : "Thao tác", "title" : "Thao tác", "defaultContent" : "<button id='updateUser' name='updateUser' class='btn btn-primary btn-edit' type='button' aria-pressed='true'>Sửa</button>"}
]
});
$('#userTable').on('click', '.btn-edit', function(){
var data = userTable.row( $(this).parents('tr') ).data();
//alert(data.user_id);
let url = "user/updateUser?id=" + data.user_id;
$("#content").load(url);
});
$(document).on('click', '#update_user', function(){
updateUser();
});
function updateUser() {
...
var data = {
...
};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
if(myObj.status == "1"){
$("#content").load("user/list");
}
}
};
xhr.open("POST", "/user/update");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(json);
}
});
The problem I occurred DataTables warning: table id=userTable - Cannot reinitialise DataTable.
Thanks you.
From DataTable Docs (first result in search engine with the warning message you provided):
DataTables has a wide range of configuration options which can be used to customise the table at initialisation time, but only at initialisation time. After a DataTable has been initialised any attempt to use these options will result in an error.
Simply put, DataTables does not allow initialisation options to be altered at any time other than at initialisation time. Any manipulation of the table after initialisation must be done through the API [...]
You are not showing how you initialize DataTable, so I can't help you further, unless you update your answer with more information.
Edit
After gathering more info from you, I now can understand what you are trying to do.
Essentially: DataTables expects it's DOM elements to be managed by itself. Once you initialize a DataTable, you should not manipulate any DOM related to it. If you want to show something like the user editing page and go back to the table after save, you need to choose one of the next 2 options:
Completely unmount the DataTable before showing the user edit page and re-initialize it after saving user data and gathering new DataTable data from server.
Don't detach DataTable DOM: show user form in a modal, or hide the DataTable instead of removing it, and unhide it again after user data has been saved. Updated data will need to be reinjected into a living DataTables, which I think will need the use of the .ajax.data initialization option.
Depends on how much data is being transferred and processed I'd choose one or the other.
Trying to get my ajax to load into data tables. I want to load 2 tables from the same ajax call but I can't even get 1 to load first. Let's get some snippet action going...
$(function() {
$("#tablepress-1").DataTable({
ajax: {
url: '/api/?action=getStats',
dataSrc: 'data',
"deferRender": true
},
"columns": [{
"instances": "Strategy"
},
{
"instances": "Exchange"
},
{
"instances": "Trades"
},
{
"instances": "PL"
},
{
"instances": "Uptime"
}
]
})
})
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="tablepress-1" class="tablepress tablepress-id-1">
<caption style="caption-side:bottom;text-align:left;border:none;background:none;margin:0;padding:0;">Edit</caption>
<tbody>
<tr class="row-1">
<td class="column-1">Strategy</td>
<td class="column-2">Exchange</td>
<td class="column-3">Trades</td>
<td class="column-4">PL</td>
<td class="column-5">Uptime</td>
</tr>
</tbody>
</table>
Since stack snippets don't support ajax data, I'll paste it here:
{"success":true,"data":{"instances":[{"Strategy":"...","Exchange":"...","Trades":"...","PL":"...","Uptime":"..."}],"trades":[{"Open":"...","Strategy":"...","Exchange":"...","Direction":"...","Size":"...","PL":"...","Close":"...","ID":"..."}]},"meta":{"botOnline":true,"threadCount":0,"balance":0.0028}}
Right now I just have my script outputting ... for each field. What happens is that the table headings disappear and no data ever gets loaded into the table.
I tried setting up a fiddle with the data source but it's my first time trying to use the echo feature. Maybe someone else knows how to do that: https://jsfiddle.net/Trioxin/kjhtn7wm/6/
I can't imagine what's wrong here. I thought I specified the json format properly but it appears not.
Regarding cross domain AJAX sources in jsfiddles you can use http://myjson.com
Your "table headings" disappear because they are not table headings. They are just a <tbody> row that will be removed as soon DataTables get some data. Do this instead:
<thead>
<tr class="row-1">
<th class="column-1">Strategy</th>
<th class="column-2">Exchange</th>
<th class="column-3">Trades</th>
<th class="column-4">PL</th>
<th class="column-5">Uptime</th>
</tr>
</thead>
You must either pass an array of objects or point to the path of that array, like dataSrc: data.instances. You could also have dataSrc: function(data) { return data.data.instances }
You define which object property that should be mapped into which column through the data option like { data: "Strategy" }:
columns: [
{ data: "Strategy" },
{ data: "Exchange" },
{ data: "Trades" },
{ data: "PL" },
{ data: "Uptime" }
]
forked fiddle -> https://jsfiddle.net/hfc10sxt/
I have a json array coming from a url:
http://blahblahblah.com/company/all, like this:
in angularjs controller, i have something like this:
$('#example-1').DataTable({
"ajax" : 'http://blahblahblah.com/company/all',
"columns": [
{"data": "companyId"},
{.....}, // I can't assign "data" name to array because it is already unnamed.
]
});
Traversing in html table_id example-1
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</tfoot>
Output:
So, my question is how do I identify the column names from above UNNAMED JSON ARRAY mentioned on top of the question, and display it in html table. Waiting for your kind response.
I am thinking to do something like this
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "http://blahblahblah.com/company/all",
"columns": [
{ "data": "companyId" },
{ "data": "legalName" },
{ "data": "dbaName" },
{ "data": "formation"}
]
} );
} );
you need to add more information to the datatable while intializing what are the keys to be shown. form more details check datatable objects
I was unable to identify the correct syntax of identifying and using the column names in my JSON array, which I did like this, and solved my problem. So now the data is displayed fine in my table, this way:
$.getJSON('http://blahblahblah/company/all', function(data) {
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId"},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I also added hyperlink to companyId like this:
$.getJSON('http://blahblahblah/company/all', function(data) {
var companyId = null;
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId", "render": function(data, type, row, meta) {
if( type==='display' ) {
companyId = data;
data = '' + data + '';
}
return data;
}},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I am thankful to all of you for helping me grab the track.
Thanks.
Actual way to do this is to use ng-repeat in the data array. And for the data fetch, use an angular service with a promise.
In the Controller
var self = this;// this is the controller which is aliased as ctrl at routing
var theData = yourService.FetchData(params).then(function(data){
self.tableData = data; // not going for the exact implementation.
},function(err){
manageError(err);// manage your errors here.
}));
In the HTML
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tr ng-repeat="var item in ctrl.tableData ">
<td>{{item.companyId}}</td>
<td>{{item.legalName}}</td>
<td>{{item.dbaName}}</td>
<td>{{item.formation}}</td>
</tr>
</table>
I Have a really complicated Array that I want to display in DataTables in order to do some research and csv export.
An extract here of one page : https://api.myjson.com/bins/w8pzl
This is the structure :
[
[
{
title : "title",
stacks: {
stackname : "stackname",
stackValue : [
"value1","value2","value3"
]
},
..... multiple article
],
.....multiple pages
]
I don't know neither how to structure the table nor how to populate it.
My first try so far :
<div id="page-content-wrapper">
<div class="container">
<div class="row">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "/",
dataSrc : ''
},
"columns" : [ {
"data" : "stackName"
}, {
"data" : "stackValue[,]"
}]
});
});
</script>
But it looks like I have to go through the all document to get my information..
If it's just not possible... I've done an easier version of my structure :
[
[
{
title : "title",
stacks: [
"value1","value2","value3"
]
},
..... multiple article
],
.....multiple pages
]
But still impossible to parse it.. i'm struggling with the two first array..
Edit with answer
Thanks to the help of the selected answer post I managed to get this code working :
$('#example').DataTable( {
"processing" : true,
"ajax": {
"url": "/",
"dataSrc" : function ( json ) {
return json.reduce(function(a, b) {
return a.concat(b)
}).map(function(value) {
return value.stacks
})
.reduce(function(a, b) {
return a.concat(b)
})
}
}
,... other configuration
You can use the ajax.dataSrc option as a function to manipulate the data returned from the server.
ajax.dataSrc
function ajax.dataSrc( data )
As a function dataSrc provides the ability to manipulate the data returned from the server from one form into another. For example, if your data is split over multiple arrays you might combine it into a single array to return for processing and display by DataTables. ...
Here is an example.
$('#example').DataTable( {
"ajax": {
"url": "https://api.myjson.com/bins/w8pzl",
"dataSrc" : function ( json ) {
return json[0].map(function(value) {
return value.stacks
})
.reduce(function(a, b) {
return a.concat(b)
})
}
},
"columns": [
{ "data": "stackName" },
{ "data": "stackValue[, ]" }
]
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</tfoot>
</table>
I am using jquery datatable in my application, plugin link https://datatables.net/
I want to populate my datatable with JSON, but I am failed.here is my code.
HTML:
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
JS:
$(document).ready(function() {
console.log("hi ready");
$('#example').DataTable({
retrieve: true,
ajax: {
url: '/ProductLicensingApplication/feature/list',
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "code" },
{ "data": "description" },
{ "data": "isActive" }
]
});
} );
my json
but I am not able to populate data into the table as the table shows no data available in the table..you can see in the image
please tell me what is the problem in my code...
As written in documentation. The ajax.dataSrc option is used to tell DataTables where the data array is in the JSON structure. An empty string is a special case which tells DataTables to expect an array.
In your case JSON is an object and you should set dataSrc : 'features'
Ahmad,
Either set dataSrc : 'features' or if possible rename the attribute name 'features' to 'data' in the response data.