How load json data on table using datatables? - javascript

I'm trying load json data on table using datatables
The return of json from php is like this:
data = {
"CLIENTES": {
"0": {
"ID": "1",
"NOME": 'GABRIEL'
},
"1": {
"ID": "2",
"NOME": 'RODRIGUES'
}
}
}
In the documentation columns data they say that I need to follow this structure:
table.DataTable({
"ajax": url,
columns: [
{"data": "CLIENTES.ID"},
{"data": "CLIENTES.NOME"}
]
});
But dont work, and we know that the right acess to de data index is this way:
{"data": "CLIENTES['0'].ID"},
{"data": "CLIENTES['1'].ID"},
But need's to be dynamically, how can I do this?

You should create new data for datatable without CLIENTES .... map is an option.
$(document).ready(function() {
data = {
"CLIENTES": {
"0": {
"ID": "1",
"NOME": 'GABRIEL'
},
"1": {
"ID": "2",
"NOME": 'RODRIGUES'
}
}
};
var newData = $.map(data.CLIENTES, function(el) { return el });
$('#example').DataTable({
data: newData,
columns: [
{"data": "ID"},
{"data": "NOME"}
]
});
});
example: https://jsfiddle.net/cmedina/7kfmyw6x/5/

If you remove the 'CLIENTES' outer array and only return an array of the results in your PHP, you will be able to refer to the values like this:
table.DataTable({
"ajax": url,
columns: [
{"data": "ID"},
{"data": "NOME"}
]
});

you can do things to an object dynamically by using for var in
var myArray = [] //an empty array
for(var i in data){
myData.push({"data": "CLIENTES[i].ID"})
myData.push({"data": "CLIENTES[i].NOME"})
}
then later you can do this
table.DataTable({
"ajax": url,
columns: myArray
});
but I suspect the way you write {"data": "CLIENTES[i].ID"} is wrong, though i havent used datatables before.
maybe something like this is more correct? it's how you usually get to object properties
for(var i in data){
myData.push({"data": data.CLIENTES[i].ID})
myData.push({"data": data.CLIENTES[i].NOME})
}

Related

How can I add Id to row with jquery ajax server-side

I need to add id property to TR of table data dynamically added with jquery ajax server-side and write data there. how can I do that. I add the Json data coming with the code below to the lines.
"ajax": {
"url": '/Siparis/SiparisleriDoldur/',
"type": 'POST',
"dataType": 'json',
"data": { liste }
},
"columns":
[
{ "data": "MusteriAdi", "name": "Müşteri Adı" },
{ "data": "MalzemeAdi", "name": " Ürün Adı" },
{ "data": "SiparisAdet", "name": "Sipariş Adedi" },
],
i want to do;
<tr id='IdNumber' data-id='IdNumber'>
<td>bla</td>
<td>bla</td>
<td>bla</td>
</tr>
Note: IdNumber is in data(json list)
Given your use of the Datatable library you can use the createdRow property of the settings to amend each row as required. Try this:
$('#yourDatatable').dataTable({
"createdRow": function(row, data, dataIndex) {
let id = data[0]; // amend 'data[0]' here to be the correct column for your dataset
$(row).prop('id', id).data('id', id);
},
"ajax": {
// ...
},
// other settings as normal...
});
I fixed my problem with;
"createdRow": function (row, data) {
var id = data.Id;
$(row).prop('id', id).data('id', id);
$(row).attr('data-id', id).data('data-id', id);
},

How can i grab an element from a row on a datatable?

I have a simple datatable that shows some JSON data, received from an API endpoint.
I added a column that will hold a button on each row of the table. This button, when hit, will fire an AJAX request with the value of id for that specific row.
This actual code works, but now, instead of only sending the value of id, i would also like to edit the table so that, when the button is hit, it will send the values of id and item for that row. Can someone give me some piece of advice on how to do that?
On another question, i've been told to use Data Attributes, but i don't really know how would i integrate this into my current code. Any advice is appreciated.
$(document).ready(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
console.log(statusVal)
callAJAX("/request_handler", {
"X-CSRFToken": getCookie("csrftoken")
}, parameters = {
'orderid': statusVal
}, 'post', function(data) {
console.log(data)
}, null, null);
return false;
});
let orderstable = $('#mytalbe').DataTable({
"ajax": "/myview",
"dataType": 'json',
"dataSrc": '',
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
},],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
return '<button type="button" class="btnClick sellbtn" data-status="replace">Submit</button>'.replace("replace", data);
}
}]
});
});
You could use the full parameter of the DataTables render function to store the values of the current seleceted row. In this way:
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
In the above code, the data-status data attribute will contains the stringified version of the current object value in base64 by using btoa(). In base64 because for some reason we cannot directly store the stringified version of the object in the button's data attribute.
Then, in the button's click event, you have to do:
Decode the stringified object by using atob().
Parse into object by using JSON.parse().
Something like this:
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
Then, when you click in the button you will see this:
So, now you can use this object to send in your callAJAX() function.
See in this example:
$(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
let dataSet = [{
"id": 1,
"item": "Item 1",
"price": 223.22
},
{
"id": 2,
"item": "Item 2",
"price": 243.22
},
{
"id": 3,
"item": "Item 3",
"price": 143.43
},
];
let orderstable = $('#myTable').DataTable({
"data": dataSet,
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
}, ],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
// Encode the stringified object into base64.
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="myTable" class="display" width="100%"></table>
Hope this helps!

Print data array value in DataTables(Server Side) column, inside string

I'm using Datatables plugin in one school project. But I can not make it work server side version. In the client side version I have some crud botons to manage the data. But I can not achieve to put that buttons in the sever side version. I try to use it with mRender wich aloud me create HTML objects. But I want to put some data array value inside this string. But I can't make it. Can someone help me with this one please.
This es what I try.
<script type="text/javascript">
$(document).ready(function () {
$('#mita').DataTable({
"columns": [
{"data": "llave"},
{"mRender": function ( data, type, full ) {
return 'Download';}},// Problem Here !!!
{"data": "llave"},
{"data": "titulo"},
{"data": "titulo"},
{"data": "fecha_inicio"},
{"data": "fecha_fin"},
{"data": "fecha_fin"},
{"data": "fecha_fin"},
{"data": "fecha_fin"}
],
"processing": true,
"serverSide": true,
"order": [[ 0, "desc" ]],
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});
});
</script>
This fix maybe help you , try this :
<script type="text/javascript">
$(document).ready(function () {
$('#mita').DataTable({
"columns": [
{"data": "llave",
"render": function ( data, type, full, meta ) {
return 'Download';
}
},
{"data": "llave"},
{"data": "titulo"},
{"data": "titulo"},
{"data": "fecha_inicio"},
{"data": "fecha_fin"},
{"data": "fecha_fin"},
{"data": "fecha_fin"},
{"data": "fecha_fin"}
],
"processing": true,
"serverSide": true,
"order": [[ 0, "desc" ]],
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});
});

Datatables: Can't interact with a row after searching

I've initiated a datatable plugin as following:
var table= $("#mytable").DataTable({
ajax: "list.json",
columns: [
{"data": "name"},
{"data": "location"},
{"data": "date"}
],
searchCols: [
{"search": "John"},
null,
null
]
});
The example above also does a pre search on the first column. Now, when the plugin is initiated I want to interact with some of its rows:
fnInitComplete: function() {
$(this).find("tr").click( ... );
}
Everything works good, UNTIL I try to interact with a row that's been searched on the table render {"search": "John"} and that was searched again after (e.g. I changed the search query to "Richard" and tried to click on one of that rows). Any ideas?
You need to use delegated event handlers because jQuery DataTables manipulates DOM on each table draw.
For example:
var table= $("#mytable").DataTable({
ajax: "list.json",
columns: [
{"data": "name"},
{"data": "location"},
{"data": "date"}
],
searchCols: [
{"search": "John"},
null,
null
]
});
$("#mytable").on("click", "tr", function(){
// Handle click event
});

How to refresh Datatable data from js array of objects

I'm using the jquery DataTables plugin to display an array of objects. I would like to clear the table and redraw using the changed data. However, the only way I've been able to do that so far is to destroy the table and reinitialize. I'd like to know if there is a simple way to refresh from JS data source. This is what I'm doing, it works but feels wrong...
if (NAMESPACE.table){
NAMESPACE.table.destroy();
}
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
]
});
if you want to clear the data present in dataTable simply call table.clear() it clears all cells in table.
and then add new data using table.row.add().draw();
table.destroy() does not removes data present in cell of table, it only destroys the current instance of dataTable you created.
Make it simpler:
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
],
"destroy": true
});

Categories