I have tried and searching lot of solution but not solve my problem, even at dataTables website. The problem is how to display nested array in json using DataTables? Fo example below, How if I just want to display l3_id: "1" data only.
I try to understand this link but not really understand. Example
There is no error at console and network tab.
DataTable not appear, including dataTables features such as search box, pagination. (The CDN/library has been imported)
JSON
{
"data": [
{
"project_id": "1",
"l1_task": [
{
"l1_id": "1",
"l2_task": [
{
"l2_id": "1",
"l3_task": [
{
"l3_id": "1",
"l3_name": "My name"
}
]
}
]
}
]
}
]
}
JS (I am applying HTML in JS)
"<table id='Layer3Table' class='table dt-responsive nowrap' style='width:100%'>"+
"<thead>"+
"<tr>"+
"<th class='text-center'>ID</th>"+
"<th class='text-center'>Activity Name</th>"+
"</tr>"+
"</thead>"+
"</table>"+
$('#Layer3Table').DataTable({
ajax: {
url: url_project_detail",
dataSrc : "data"
},
columns: [
{ data : "l1_task.0.l2_task.0.l3_task.0.l3_id" },
{ data : "l1_task.0.l2_task.0.l3_task.0.l3_name" },
],
});
Either define your table, including all tbody content in HTML, then use DataTables to enable the search etc features. If you do it this way you don't need to set the url or columns (although you can still set other options).
$('#Layer3Table').DataTable();
Or if you want to make use of the url and column features, create the basic table structure in HTML
<table id='Layer3Table' class='table dt-responsive nowrap' style='width:100%'>
<thead>
<tr>
<th class='text-center'>Project ID</th>
<th class='text-center'>Project Name</th>
<th class='text-center'>Project Description</th>
<th class='text-center'>Project Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Then set up your DataTable separately in JavaScript.
$('#Layer3Table').DataTable( {
ajax: {
url: url_project_detail,
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: "application/json",
dataSrc : "data",
},
columns: [
{ data : "l3_id", "className": "text-center" },
{ data : "l3_name", "className": "text-center" },
{ data : "l3_description", "className": "text-center" },
{ data : "l3_status", "className": "text-center" }
],
});
What you appear to be doing is looping over your results and creating a DataTable for each of them, which is why it doesn't understand.
Related
This is in the variable "test":
{"data":[{"HistChar_ID":"4","Vorname":"Garnier","Nachname":"de
Naplouse"},{"HistChar_ID":"2","Vorname":"Robert","Nachname":"de
Sable"},{"HistChar_ID":"7","Vorname":"Ibn","Nachname":"Dschubair"},{"HistChar_ID":"6","Vorname":"Baha
ad-Din","Nachname":"ibn
Schaddad"},{"HistChar_ID":"1","Vorname":"Richard","Nachname":"L\u00f6wenherz"},{"HistChar_ID":"5","Vorname":"Wilhelm","Nachname":"von
Montferrat"}]}
HTML:
<table id="example" class="display" style="width:100%">
<thead class="thead1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</thead>
<tfoot class="tfoot1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</tfoot>
</table>
An the following Code Wont fill the Datatable.
$('#example').DataTable({
data: test,
columns: [
{ data: 'HistChar_ID' },
{ data: 'Vorname' },
{ data: 'Nachname' },
]
it throws an Error like this:
DataTables warning: table id=example - Requested unknown parameter
'HistChar_ID' for row 0, column 0. For more information about this
error, please see http://datatables.net/tn/4
I tried so much. But if i take whats inside of "test" and put it into a php and use ajax it works just fine with this.
$('#example').DataTable({
ajax: 'RESOURCES/PHP/Searchfield.php',
columns: [
{ data: 'HistChar_ID' },
{ data: 'Vorname' },
{ data: 'Nachname' },
]
PHP/Searchfield
include 'connection.php';
$searchstuff = $_GET['Searchfield'];
$sql = "select * FROM historischercharacter WHERE Vorname LIKE '%$searchstuff%' OR Nachname LIKE '%$searchstuff%' ORDER BY Nachname" ;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode(array('data'=>$emparray));
mysqli_close($conn);
Can someone explain me why? Is it impossible to fill the Datatable with a variable?? I just dont get it...
If you look at the examples in the documentation, the hard-coded array being passed into the table doesn't have the outer data property, it's just an array by itself - see https://datatables.net/examples/data_sources/js_array.html . You can see the same thing here as well: https://datatables.net/reference/option/data
The requirements when defining an AJAX data source are different. As per the example at https://datatables.net/reference/option/ajax by default you must supply an object with a "data" property as per the structure you've shown us in your question.
So it's simply that the requirements for each type of data source are different. Always read the documentation!
Demo of how to set the data source using a variable, with your variable. Note the absence of the "data" property...instead "test" is just a plain array:
var test = [{
"HistChar_ID": "4",
"Vorname": "Garnier",
"Nachname": "de Naplouse"
}, {
"HistChar_ID": "2",
"Vorname": "Robert",
"Nachname": "de Sable"
}, {
"HistChar_ID": "7",
"Vorname": "Ibn",
"Nachname": "Dschubair"
}, {
"HistChar_ID": "6",
"Vorname": "Baha ad-Din",
"Nachname": "ibn Schaddad"
}, {
"HistChar_ID": "1",
"Vorname": "Richard",
"Nachname": "L\u00f6wenherz"
}, {
"HistChar_ID": "5",
"Vorname": "Wilhelm",
"Nachname": "von Montferrat"
}];
$('#example').DataTable({
data: test,
columns: [{
data: 'HistChar_ID'
},
{
data: 'Vorname'
},
{
data: 'Nachname'
},
]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead class="thead1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</thead>
<tfoot class="tfoot1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</tfoot>
</table>
Here is an example using a JavaScript variable which does not require you to change the data you show in your question:
var test = { "data": [ { ... }, { ... }, ... ] };
In the above structure, each element in the array [ ... ] contains the data for one table row.
In this case, the DataTable uses the data option to specify where that array can be found:
data: test.data
Here is the runnable demo:
var test = {
"data": [{
"HistChar_ID": "4",
"Vorname": "Garnier",
"Nachname": "de Naplouse"
}, {
"HistChar_ID": "2",
"Vorname": "Robert",
"Nachname": "de Sable"
}, {
"HistChar_ID": "7",
"Vorname": "Ibn",
"Nachname": "Dschubair"
}, {
"HistChar_ID": "6",
"Vorname": "Baha ad-Din",
"Nachname": "ibn Schaddad"
}, {
"HistChar_ID": "1",
"Vorname": "Richard",
"Nachname": "L\u00f6wenherz"
}, {
"HistChar_ID": "5",
"Vorname": "Wilhelm",
"Nachname": "von Montferrat"
}]
};
$(document).ready(function() {
$('#example').DataTable({
data: test.data,
columns: [
{ data: 'HistChar_ID' },
{ data: 'Vorname' },
{ data: 'Nachname' },
]
} );
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%">
<thead class="thead1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</thead>
<tfoot class="tfoot1">
<tr>
<th class="th1">HistChar_ID</th>
<th class="th2">Vorname</th>
<th class="th3">Nachname</th>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
JavaScript Data Sources
In the above example, the data is sourced from a JavaScript variable - so at the very least you always need to tell DataTables what the name of the JS variable is, using the data option.
And, you may also need to tell DataTables where the array of row data can be found in that variable. This is what we needed to do in the above example.
If the JavaScript variable had been structured like this (an array, not an object containing an array)...
var test = [ { ... }, { ... }, ... ];
...then in that case, we only need to use data: test in the DataTable.
Ajax Data Source
For Ajax-sourced data, things are slightly different. There is no JavaScript variable - there is only a JSON response.
By default, if that JSON response has the following structure (an array of objects called "data" - or an array of arrays)...
{ "data": [ { ... }, { ... }, ... ] }
...then you do not need to provide any additional instructions for DataTables to locate the array. It uses "data" as the default value.
Otherwise if you have a different JSON structure, you need to use the Ajax dataSrc option to specify where the array is in the JSON response.
For the above example, if you do not provide the dataSrc option, that is the same as providing the following:
ajax: {
url: "your URL here",
dataSrc: "data" // this is the default value - so you do not need to provide it
}
This is why your Ajax version "just works" when you only provide the URL:
ajax: 'RESOURCES/PHP/Searchfield.php'
DataTables is using the default value of data to find the array it needs.
And this is why it doesn't work when you use a JavaScript variable called test with data: test.
So, for JavaScript-sourced data, there is no default value. You always have to provide the JavaScript variable name - and maybe additional info for the location of the array in the varaible.
But for Ajax-sourced data, there is a default value (data) - and I believe this is only provided for backwards compatibility with older versions of DataTables.
I am populating a table with datatables. The table has four columns always. But I need to add another column which can be shown or hidden based on boolean value.
My code so far:
{% show_extra_fields_button = show_extra_fields_bool %}
<table class="display" id="fields_datatable" class="fields_datatable">
<thead>
<tr>
<th>Name</th>
<th>Place</th>
<th>Email</th>
<th>Phone</th>
<th>Add Extra</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="/static/js/vendor/datatables.min.js"></script>
<script>
$(document).ready(function() {
$("#fields_datatable").dataTable({
ajax: {
"processing": true,
"dataSrc": "",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
]
})
if (show_extra_fields_button) {
$("#fields_datatable tr").each(function(){
$(this).append("<td><button>Add Extra</button</td>");
});
}
});
</script>
Here I would want to show the Add Extra column based on the boolean value. I want the header and the column values which will be buttons to be added using js.
How can I do that?
You can use data tables built-in functionality.
To add a button column you can use the following column definition:
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
Then use initComplete callback to set the columns' visibility once table has fully been initialised, data loaded and drawn:
$("#fields_datatable").dataTable({
ajax: {
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
],
"initComplete": function (settings, json) {
// get instance of datatable
table = settings.oInstance.api();
// get column using its name and set visibility
table.column('buttonColumn:name').visible(show_extra_fields_button);
}
});
You can put - instead of deleting that <td> for example <td>-</td>
You can add to the table header just the same way you are adding to the table body.
if (show_extra_fields_button) {
$('#fields_datatable thead tr').append('<th>Add Extra</th>')
}
Execute it just one time.
I am fetching json data through ajax for my datatable and performing a ajax reload every 2 seconds which updates the datatable values but I want to change the color of all the values that changed during the reload. How can I do that?
I would like the output to be like this
https://www.dailyfx.com/forex-rates?ref=TopRates
This is my code
<table id="example" class="pgnTable table" style="width:100%">
<thead>
<tr>
<th>First value</th>
<th>Second value</th>
<th>Third value</th>
<th>Fourth value</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function() {
$('#example').DataTable({
"ajax": {
"url": "/pktd",
"dataType": "json",
"dataSrc": "data",
"contentType": "application/json"
},
"columns": [{
"data": "first"
},
{
"data": "second"
},
{
"data": "third"
},
{
"data": "fourth"
}
]
});
setInterval(function() {
$('#example').DataTable().ajax.reload();
}, 2000);
});
</script>
You could set a CSS Class when you see a value change, with CSS Keyframes you can also add some color changing animations like the forex site.
JQuery has functions built in for adding and removing classes based on an elements ID like you have above.
I have a pretty simple datatables object. I bind it to an array of objects, specify the data fields and it works. The problem is when I try to implement the CSV export. It always only wants to export the first row of the table. Any ideas?
Here's where my code stands at the moment. And to be sure, I've made sure that the button and select libraries are included but that has made no difference.
<table id="tblData" style="display:none;">
<thead>
<tr id="trDataTableHeader">
<th data-s-type="string">Name</th>
<th data-s-type="string">Address</th>
<th data-s-type="string">Phone</th>
<th data-s-type="string">Website</th>
<th data-s-type="string">Types</th>
</tr>
</thead>
</table>
...
table = $('#tblData').DataTable({
dom: 'rtB',
data: tableData,
columns: [
{ "data": "name" },
{ "data": "address" },
{
"data": "phone_number",
defaultContent: ""
},
{
"data": "website",
defaultContent: ""
},
{
"data": "types",
defaultContent: ""
},
],
buttons: [{
extend: "csv",
text: "Export",
exportOptions: {
modifier: { search: "none", selected: false}
}
}],
select: false,
lengthChange: false,
sort: false,
paging: false
});
After a lot of digging, I made an accidental discovery when I removed the column data type specifications. I got an error message that str.replace is not a function.
Turns out that the parseInt and parseFloat base functions were being overridden by another developer on that page and was causing a problem but DataTables was too graceful to tell me.
This is why you don't override base javascript functions unless you absolutely have to.
This is linked to the question here. However, my case is a bit different. I would like to implement the same datatables example from the other question which is here. As you can see you have to pass the column names to be able to initialize the table headers like below
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
The problem is that I would not know the header names beforehand as they will change. I've tried initializing the column names when I get the data from ajax like below using a 3rd variable (see where it says 'pay attention to this line' but this doesn't work.
//PAY ATTENTION TO THIS LINE
var columnsHeaders = [];
var ab = $('#dynamicScenarioTable').DataTable({
"bDestroy": true,
"dom": 'T<"clear">lfrtip',
"ajax": {
"type": "POST",
"url": "dynamicScenario.htm",
"data": tags,
"dataType": "json",
"dataSrc": function(json){
//PAY ATTENTION TO THIS LINE
columnsHeaders.push({"data": json.header });
return json.vals;
},
"error": function(exception)
{
displayMessageOnError();
}
},
//PAY ATTENTION TO THIS LINE
"columns": [columnsHeaders],
tableTools: tableDefaultS.tableTools
});
Any ideas?
You can add a data-source attribute to the TH tags that are built on your table header. You can then have jQuery read those and construct the array to send into the DataTable constructor.
<tr>
<th data-source="name">Name</th>
<th data-source="position">Postion</th>
<th data-source="start_date">Start Date</th>
</tr>
Then in your JavaScript do something like this to construct the array
var columnsHeaders = [];
$("#dynamicScenarioTable thead th").each(function() {
colmnsHeaders.push(
{
data : $(this).data("source")
}
);
});
// construct your DataTable after this