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!
Related
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);
},
I have some code to display data using Datatables and it works fine. How do I get a value from column id?
I want to call window.open() to print the content of data on the datatables. I expect the data shown to be taken from array { "data": "id" } to passing on window.open(url)
$(document).ready(function() {
var table = $('#load_data').DataTable({
"ajax": {
"url": "data.php",
"dataSrc": ""
},
"columns": [{
"dataId": "id" // I want to get this value
}, {
"data": "tgl"
}, {
"data": "name"
}, {
"data": "company"
}, {
"data": "status"
}, {
"data": null,
"defaultContent": "<a href='javascript:void(0)' id='btn-print' class='btn btn-primary btn-sm'>print</a>",
}]
});
setInterval(function() {
table.ajax.reload(null, false);
}, 5000);
$('#load_data').on('click', 'tbody #btn-print', function() {
var getID = table.cell(this).data(); //try to catch id value variable
var url = "print.php?id=" + getID; //i want to pass getID variable to this variable
window.open(url, "_blank", "dialog=yes,minimizable=no,scrollbars=no,resizable=no,top=400,left=400,width=350,height=450");
console.log(getID);
});
});
There are many ways you can get data from the table.
cell.data()
columns.data()
rows.data()
Here is an example:
var ids = table.columns( 0 ).data(); //Get all Ids in to an array
I have a js data table that I have implemented for pagination of data. It uses the jQuery data table. The data is being displayed correctly. However, I want to add an element within the first row of the data table.
Before I added it like this : <td>#Html.ActionLink(item.CarId, "Detail", "Cars", new { id = item.CarId},null)
<span class="dt-expand-btn js-expand-btn">+</span></td>
What I want to add within the td of the js is : <span class="dt-expand-btn js-expand-btn">+</span>
var carsDataTable = $('.js-cars-lists').DataTable({
"ajax": {
"url": "/Cars/CarsPagination",
"processing": true,
"serverSide": true,
"language": {
"paginate": {
"previous": '<i class="material-icons">chevron_left</i>',
"next": '<i class="material-icons">chevron_right</i>'
}
},
"order": [0, "asc"],
"type": "POST",
"datatype": "json"
},
"columns": [
{
"data": "CarId", "name": "CarId", "autowidth": true,
"render": function (data, type, row, meta) {
$(row.CarId).css('color', 'red');
return '' + row.CarId + '';
}
},
{ "data": "CarName", "name": "CarName", "autowidth": true },
Could someone please help me to achieve this ? Also, paginate icons are not appearing. Please help.
jQuery DataTable has a function of render it accepts 4 parameters function(data, type, row) which you can control the rendering of your rows. You can now check the rows of a table and add your element in it.
You can use columnDefs method and then render:
...
columnDefs: [{
"render": function(data, type) {
return '<span class="dt-expand-btn js-expand-btn">+</span>';
},
"targets": 0
}]
...
targets refers to the index of the table column (since you are referring to the 1st column) set it to 0
I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)
I have an issue with the reinitialisation of my datatable. My code below works by pulling in a json from getOrderStatus.php and upon success of this puts all the json data into javascript variables and then from this i can set these variables to div tags and display the data i need on my webpage. However the Datatable cannot be reinititalised once the ajax loop runs and displays the following error message "DataTables warning: table id=mytable - Cannot reinitialise DataTable". I believe i need a way to kill the table and recreate it upon the ajax refresh however i cant seem to find a way to do this ?
$(document).ready(function ajaxLoop(){
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function updateOrder(data) //on reciept of reply
{
var OrdersSubmitted = data.OrderStatus[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data.OrderStatus[0].FULFILLED; //get Orders Fulfilled count
var LastTransaction = data.LastTransaction[0]; //get Last Transaction
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html(OrdersSubmitted);
$('#OrdersFulfilled').html(OrdersFulfilled); //Set output html divs
$('#mytable').dataTable({
"data": LastTransaction,
"aging": false,
"searching": false,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
setTimeout(ajaxLoop, 2000);
}
});
});
Did you try using "bDestroy": true.
$('#mytable').dataTable({
"data": LastTransaction,
"aging": false,
"searching": false,
"bDestroy": true,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
Another way is if you check if datatable is already init. on your table
var table = $('#mytable');
if ($.fn.DataTable.fnIsDataTable(table)) {
//It's already a datatable
//clear and destroy
table.dataTable().fnClearTable();
table.dataTable().fnDestroy();
}
**It seems your are using latest datatable version:**
then option should be destroy:true (aging should be changed to paging):
$('#mytable').dataTable({
"data": LastTransaction,
"paging": false,
"searching": false,
"destroy": true,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
and check on existing datatable would be:
if($.fn.DataTable.isDataTable("#myTable"))
{
$('#myTable').DataTable().clear().destroy();
}