How to get Row data after a button click in datatables - javascript

can anyone help me on how to get a single row data on a click event.
This is the table which is dynamically populated after Success function in AJAX call is executed
<div class="table-responsive table-wrap tableFixHead container-fluid">
<table class="table bg-violet dT-contain" id="datatable" >
<thead class="thead-dark">
<tr>
<th>No.</th>
<th>Main</th>
<th>Shrinked</th>
<th>Clicks</th>
<th>Disable</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr class="bg-violet">
</tr>
</tbody>
</table>
</div>
<script src="scripts/jquery-3.5.1.min.js"></script>
<script src="scripts/jquery.dataTables.min.js"></script>
<script src="scripts/dataTables.bootstrap4.min.js" defer></script>
<script src="scripts/dashboard.js" defer></script>
This is my ajax success function
success: function(data){
$('#datatable').dataTable({
data: data,
"autoWidth": true,
columns: [
{'data': 'id'},
{'data': 'main'},
{'data': 'shrinked'},
{'data': 'clicks'},
{"defaultContent": "<button id='del-btn'>Delete</button>"}
]
})
}
I am adding a delete button to each row dynamically, but can't seem to fetch row data using it.
I tried this method with some tweaks to my success function
$('#datatable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] );
} );
But this didn't seem to work.
The JSON data returning from the AJAX call is in this format:
[{"id":"12","main":"ndkekfnq" ...}, {.....}]
I also added an onclick function on the delete button to try to fetch data but that also didn't work.
EDIT: whole AJAX request
$(document).ready(()=>{
$.ajax({
url: 'URL',
method: 'post',
dataType: 'json',
data: {
"email": window.email,
"token": window.token
},
success: function(data){
let table = $('#datatable').dataTable({
data: data,
"autoWidth": true,
columns: [
{'data': 'id'},
{'data': 'main'},
{'data': 'shrinked'},
{'data': 'clicks'},
{"defaultContent": "<button id='dis-btn' class='btn btn-warning'>Disable</button>"},
{"defaultContent": "<button id='del-btn' class='btn btn-danger'>Delete</button>"}
]
})
$('#datatable tbody').on('click', "#del-btn", function() {
let row = $(this).parents('tr')[0];
//for row data
console.log(table.row(row).data().id);
});
}
})
})
What would be the correct way to do this? Thank you

You need to use column.render instead o defaultContent and then get the data on an outside function, you need to render a button at the render of the table:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
rel="stylesheet"
href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"
/>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="table-responsive table-wrap tableFixHead container-fluid">
<table class="table bg-violet dT-contain" id="datatable" >
<thead class="thead-dark">
<tr>
<th>No.</th>
<th>Main</th>
<th>Shrinked</th>
<th>Clicks</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr class="bg-violet">
</tr>
</tbody>
</table>
<script>
$('#datatable').dataTable( {
"data": [{'id':20,'main':'hola','shrinked':false,'clicks':2000},{'id':21,'main':'hola','shrinked':false,'clicks':283000}],
"autoWidth": true,
"columns": [
{"data": "id"},
{'data': 'main'},
{'data': 'shrinked'},
{'data': 'clicks'},
{"data": "id",
"render": function ( data, type, row, meta ) {
return '<button data-id="'+data+'" onclick="deleteThis(event)">Delete</button>'
}
}
]
} )
function deleteThis(e){
console.log(e.target.getAttribute('data-id'))
}
</script>
</body>
</html>
Haven't tried, but based on Datatables docs, this should work, let me know if it worked.

Here is working code for you. You need to set the datatables in a var.
Use that var table to look for clicked row which will $(this).parents('tr')[0] and use .data.id to the clicked item id
I have recreated the your example and its working fine. Just set you ajax response to the data.
Demo
//Ajax Data
var data = [{
"id": "10",
"main": "ndkekfnq",
"shrinked": "ndkekfnq",
"clicks": "ndkekfnq"
}, {
"id": "12",
"main": "Something",
"shrinked": "Data",
"clicks": "Ha"
}]
//Data Table
var table = $('#datatable').DataTable({
data: data,
columns: [{
'data': 'id'
},
{
'data': 'main'
},
{
'data': 'shrinked'
},
{
'data': 'clicks'
},
{
"defaultContent": "<button id='del-btn'>Delete</button>"
}
]
});
$('#datatable tbody').on('click', "#del-btn", function() {
var row = $(this).parents('tr')[0];
//for row data
console.log(table.row(row).data().id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js" integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" integrity="sha512-1k7mWiTNoyx2XtmI96o+hdjP8nn0f3Z2N4oF/9ZZRgijyV4omsKOXEnqL1gKQNPy2MTSP9rIEWGcH/CInulptA==" crossorigin="anonymous" />
<div class="table-responsive table-wrap tableFixHead container-fluid">
<table class="table bg-violet dT-contain" id="datatable">
<thead class="thead-dark">
<tr>
<th>No.</th>
<th>Main</th>
<th>Shrinked</th>
<th>Clicks</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr class="bg-violet">
</tr>
</tbody>
</table>

#Javier 's answer is a very good way to solve the OP's issue. Another way, if you don't want to include id field twice, would be like this:
"columns": [
{"data": "id"},
{'data': 'main'},
{'data': 'shrinked'},
{'data': 'clicks'},
{"data": null,
"render": function ( data, type, row, meta ) {
return '<button data-id="' + data.id + '" onclick="deleteThis(event)">Delete</button>'
}
}
]

Related

Get MySQL Query using Ajax then Inserting Result to Data Table on button click

I want to ask how can I insert my sql query to the html datatable table body.
This is my present code:
AJAX Query for loading datatable after button click:
$(document).on('click','#filtersearch',function(e){
e.preventDefault();
$.ajax({
url:"index.php",
method:"POST",
data:{
formula:"filtersearch"
},
dataType:"json",
beforeSend:()=>{
$('.load_spinner').removeClass('d-none');
},
success:function(res){
$('.load_spinner').addClass('d-none');
select_d = res;
console.log(res);
var str ="";
if (!$.isEmptyObject(select_d)) {
select_d.forEach((x)=>{
str += `<tr>
<td>${x.assetid}</td>
<td>${x.assetcode}</td>
<td>${x.assetserial}</td>
<td>${x.assetname}</td>
<td>${x.assettype}</td>
<td>${x.assetcat}</td>
<td>${x.dpurchased}</td>
<td>${x.price}</td>
<td>${x.dperiod}</td>
<td>${x.finprice}</td>
<td>${x.status}</td>
<td>${x.assetage}</td>
<td>${x.location}</td>
</tr>`;
})
}
data_table("#table_index","#tbody_index",str);
}
})
})
Javascript for Datatable Content transfer from AJAX:
function data_table(table_name,tbody_name,data_tbody) {
$(table_name).DataTable().destroy();
$(tbody_name).empty().html(data_tbody);
$(table_name).DataTable();
};
Datatable HTML cointainer that will get the ajax query:
<table class="table table-bordered" id="table_index" width="100%" cellspacing="0">
<thead>
<tr>
<th>No.</th>
<th>Asset Code</th>
<th>Asset Serial</th>
<th>Asset Name</th>
<th>Category</th>
<th>Type</th>
<th>Date Purchased</th>
<th>Initial Price (PHP)</th>
<th>Depreciation Period</th>
<th>Final Price (PHP)</th>
<th>Status</th>
<th>Classification</th>
<th>Location</th>
</tr>
</thead>
<tbody id="tbody_index">
</tbody>
</table>
PHP code for database query:
<?php
include 'include/dbconfig.php';
$sql = 'SELECT * FROM tbl_assets';
$result = mysqli_query($conn, $sql);
$formula ='';
if (isset($_POST['formula'])) {
$formula = $_POST['formula'];
}
switch ($formula) {
case 'filtersearch':
$result = filtersearch();
$supData = array();
while ($row = $result->fetch_assoc()) {
$supData[] = $row;
}
echo json_encode($supData);
break;
default:
break;
}
function filtersearch()
{
include 'include/dbconfig.php';
$query = mysqli_query($conn,"SELECT * FROM tbl_assets");
return $query;
}
?>
I just want to ask what is wrong with my code since the script doesn't show the values of Tbody as intended. Thanks.
I found a solution after manipulating the pages instead.
Instead of coding all of them in one page, I tried creating another page (switchcase.php) that contains the PHP files and it worked as intended.
Just a hunch, but I think ajax doesn't accept urls of the same page. I don't know if thats how it works but yeah, I changed the url to switchcase.php and it worked.
if you using datatable with ajax and php try this way
<script>
$(function(){
$('#table_index').dataTable( {
'lengthMenu': [[10, 25, 50, 100, 500], [10, 25, 50, 100, 500]],
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'order': [[ 1, "desc" ]],
'ajax': {
'url': 'index.php'
},
"columns": [
{ "data": "id" },
{ "data": "asset_code" },
{ "data": "asset_serial" ,'bSortable': false},
{ "data": "asset_name" ,'bSortable': false},
{ "data": "category_id" ,'bSortable': false},
{ "data": "type", 'bSortable': false},
{ "data": "date_purchased"},
{ "data": "initial_price" },
{ "data": "depreciation_period" },
{ "data": "final_price" },
{ "data": "status" ,'bSortable': false},
{ "data": "classification" },
{ "data": "location" }
]
});
$.fn.dataTable.ext.errMode = 'none';
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover table-nomargin table-condensed" id="table_index">
<thead>
<tr>
<th>No.</th>
<th>Asset Code</th>
<th>Asset Serial</th>
<th>Asset Name</th>
<th>Category</th>
<th>Type</th>
<th>Date Purchased</th>
<th>Initial Price (PHP)</th>
<th>Depreciation Period</th>
<th>Final Price (PHP)</th>
<th>Status</th>
<th>Classification</th>
<th>Location</th>
</tr>
</thead>
<tbody></tbody>
</table>

Add delete event inside delete button to each row of Datatables on Angular and add background-color into button

I am able to put a button inside each row of data tables but the button doesn't have any function, and I didn't know how to add delete event to that button. can someone help me? hope you give me the demo too ;)
*ps: also, how to put background-color on print, export button. className : red(on TS) and .red{ background-color : red;}(on CSS) didn't work out :/
*another ps : i'm using datatables.net
TS File
products: any = (data as any).default;
ngOnInit(): void {
this.dtOptions = {
ajax: {
url: '',
type: 'GET',
dataType: 'json',
},
columns: [
{
title: 'ID',
data: 'id',
},
{
title: 'Name',
data: 'name',
},
{
title: 'Gender',
data: 'gender',
},
{
title: 'Option',
data: null,
defaultContent:
'<button class="btn-delete type="button">Delete</button>',
targets: -1,
},
],
dom: 'Bfrtip',
buttons: [
{ extend: 'excel', text: 'Export' },
{
text: '<i class="fa fa-files-o"></i>',
action: function (e, dt, node, config) {
dt.ajax.reload();
},
},
{
extend: 'print',
text: 'Print',
},
],
};
}
html
<table
datatable
[dtOptions]="dtOptions"
class="mc row-border hover">
</table>
You can check this Demo
you need to rerender after delete process. You can add button like below and give function to it.
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of persons">
<td>{{ person.id }}</td>
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
<td><button class="btn-delete" (click)="deleterow(person)">Remove</button> </td>
</tr>
<tr *ngIf="persons?.length == 0">
<td colspan="4" class="no-data-available">No data!</td>
</tr>
</tbody>
</table>
in component you need rerender function
deleterow(person){
console.log(person);
//here do delete event
const that = this;
this.rerender()
}
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
this.dtTrigger.next();
});
}
and change your afterinit with
ngAfterViewInit(): void {
this.dtTrigger.next();
}

How to replace standard bootstrap table with dataTables in jQuery?

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.

How can i display on a datatable array data using Ajax?

I'm using a MongoDB database to store some data. I now want to display this data on a HTML Datatable.
The data i'm trying to use is stored in arrays, here is how it is structured:
data: [[1848, 84857], [4944, 4949], [34, 65], [3566, 78], .... ]
$(document).ready(function() {
var table = $('#mytable').DataTable({
"serverSide": true,
"ajax": "/endpoint/?format=datatables",
"columns": [
{"data": 'data'},
]
});
setInterval( function () {
table.ajax.reload();
}, 10000 );
});
The problem with my actual code is that it will display the datatable like this:
DATA:
[[1848, 84857], [4944, 4949], [34, 65], [3566, 78], .... ]
While i would like it like this:
DATA:
1848, 84857
4944, 949
36, 65 and so on
How can i fix this issue? I was thinkin with a foor loop, but i don't really know how to do that, since i'm calling the data straight in the table variable.
The json response is something like this:
{"data":"[[11756.53, 2.419583] .....
You are using array of array data, just use index key to map your columns:
"columns": [
{"data":0},
{"data":1}
]
Awesome Example below:
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
$.mockjax({
url: "/endpoint/?format=datatables",
response: function(settings) {
this.responseText = {
"draw": settings.data.draw,
"recordsTotal": 4,
"recordsFiltered": 4,
"data": [
[randomIntFromInterval(400, 8000), 84857],
[4944, 4949],
[34, 65],
[3566, 78]
]
}
}
});
var editable=false;
$(document).ready(function() {
var table = $('#mytable').DataTable({
"serverSide": true,
"ajax": "/endpoint/?format=datatables",
"columns": [
{"data":0},
{"data":1}
]
});
setInterval( function () {
table.ajax.reload();
}, 10000 );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="mytable" class="display nowrap" width="100%">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Col1</th>
<th>Col2</th>
</tr>
</tfoot>
</table>

Why my dataTables in bootstrap don't see the data included?

I want to create a dynamic table in bootstrap/jquery, similar to this one
In this example the data is hardcoded, so I thought about changing it with the data that comes from json. Additionally, each row in table has to have a hyperlink added, so my jquery code is as follows:
$('#dataTables-example').DataTable({
responsive: true
});
var data = '[{"number":"1","id":"2","price":"100.70","date":"2015-10-18 03:00:00","hidden":"21"},
{"number":"2","id":"2","price":"88.20","date":"2015-10-18 04:00:00","hidden":"22"}]';
json = JSON.parse(data);
$.each(json, function(i, v) {
$('<tr/>', {
html: [$('<td/>', {
text: v.number
}), $('<td/>', {
text: v.id
}), $('<td/>', {
text: v.price
}), $('<td/>', {
text: v.date
}), $('<td/>', {
html: [
$('<a/>', {
href: '#',
class: 'show-details',
text: 'show details',
data: { id: v.hidden },
click: function() {
var id = $(this).data('id');
console.log(id);
alert(id);
}
})
]
})]
}).appendTo('#dataTables-example tbody')
})
In my html I hardcoded the header of the table:
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>number</th>
<th>id</th>
<th>price</th>
<th>date</th>
<th>show details</th>
<th style="display:none;">hidden identifier</th>
</tr>
</thead>
<tbody></tbody>
</table>
and later on thanks to my script I'm appending rows to the table. Simple as that.
However, as you can see in my fiddle:
http://jsfiddle.net/uo8rc5qL/6/
there is a problem, because since the data is not hardcoded, the table thinks there are no rows and displays the specific message there No data available in table. Also, when I click any column name to sort that data - content disappears, since the table thinks there's nothing to display after sorting...
How can I fix this situation?
This is because you're just adding the data to the table, not the underlying datatable source. The solution is to let datatables handle the loading of the data:
$('#dataTables-example').DataTable({
responsive: true,
"data": JSON.parse(datasrc),
"columns": [
{ data: 'number' },
{data: 'id'},
{data: 'price' },
{ data: "date" },
{
"data": "null",
"defaultContent": "<a>click</a>"
},
{ data: "hidden" }
]
});
Working example: JSFIDDLE
Always go through the API! Insert new rows using table.row.add([..]) instead of the jQuery $('<tr>', {... approach :
$.each(json, function(i, v) {
var row = table.row.add([v.number, v.id, v.price, v.date, '<a>show details</a>']);
table.cells({ row: row.index(), column: 4 }).nodes().to$().find('a')
.attr('href', '#')
.addClass('show-details')
.css('cursor', 'pointer')
.data('id', v.hidden)
.on('click', function() {
var id = $(this).data('id');
console.log(id);
alert(id);
})
table.draw();
})
forked fiddle -> http://jsfiddle.net/2wujw71x/1

Categories