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
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 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!
On document.ready, my Datatable loads accordingly.
What I need to do is build a feature that reloads the Datatable if the user conducts a search.
So the Datatable loads like this:
$(document).ready(function()
{
$('#searchSubmit').on('click', function() // used for searching
{
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
var searchtli = $('#searchtli').val();
if(searchbooking == "" && searchquote == "" && searchtli == "")
{
$('.message').text('You did not enter any search criteria.');
return false; // making sure they enter something
}
else
{
$.post('api/searchAll.php', {searchbooking:searchbooking, searchquote:searchquote, searchtli:searchtli}, function(data)
{
// what do i do here???
// how do I get the return results to load
});
}
});
// if the user does not enter any search parameters, load everything
$('#example1').DataTable({
"ajax": {
"url": "api/displayQnams.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
// and so on
});
});
As you will see in the above code, when the document is ready, if the user does not conduct a search, I load all of the data from the process called 'displayQnams.php'.
But if the user conducts a search, the parameters are sent to another process called 'qnamsSearch.php'.
How do I reload the datatable with the search results from 'qnamsSearch.php'?
I tried to create a variable from inside the post:
var dataUrl = data;
And I tried to call that variable in the ajax call:
"ajax": {
"url": dataUrl,
"type": "POST",
"dataSrc": ''
}
But the Datatable will not display anything and there are no console errors.
How can I make this work?
You can try using this.
After user click search button, below is the flow:
Clear datatables - datatables clear()
Add new data to the table - datatables rows.add()
Adjust column size (optional) - datatables adjust.columns()
Redraw back datatable with new data - datatables draw()
$(document).ready(function(){
var datatable = $('#example1').DataTable({
"ajax": {
"url": "api/displayQnams.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]]
});
$('#searchSubmit').on('click', function(){
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
var searchtli = $('#searchtli').val();
if(searchbooking == "" && searchquote == "" && searchtli == ""){
$('.message').text('You did not enter any search criteria.');
return false; // making sure they enter something
} else {
$.post(
'api/searchAll.php',
{ searchbooking:searchbooking, searchquote:searchquote, searchtli:searchtli },
function(data) {
var newData = data;
datatable.clear().draw();
datatable.rows.add(newData); // Add new data
datatable.columns.adjust().draw(); // Redraw the DataTable
});
}
});
});
I am using jQuery DataTable to display huge amount of data in a table. I am getting data page wise on Ajax request like this:
var pageNo = 1;
$('#propertyTable').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "${contextPath}/admin/getNextPageData/"+pageNo+"/"+10,
"columns": [
{ "data": "propertyId" },
{ "data": "propertyname" },
{ "data": "propertyType" },
{ "data": "hotProperties" },
{ "data": "address" },
{ "data": "state" },
{ "data": "beds" },
{ "data": "city" },
{ "data": "zipCode" }
],
"fnDrawCallback": function () {
pageNo = this.fnPagingInfo().iPage+1;
alert(pageNo); // this alerts correct page
}
} );
and here is the spring controller:
#RequestMapping(value="/getNextPageData/{pageNo}/{propertyPerPage}")
public #ResponseBody PropertyDatatableDto getNextPageData(#PathVariable Integer pageNo, #PathVariable Integer propertyPerPage) {
System.out.println("called");
System.out.println(pageNo); // this always prints 1, what i need is current pageNo here
PropertyDatatableDto datatableDto = new PropertyDatatableDto();
//datatableDto.setDraw(1);
datatableDto.setRecordsTotal(100);
datatableDto.setRecordsFiltered(100);
datatableDto.setData(adminService.getAllPropertyList());
return datatableDto;
}
The problem is that when I change page in table it alerts correct pageNo on page (in JavaScript), but in spring controller I am always getting the initial value assigned to the variable pageNo and not the current page number.
How do I pass pageNo dynamically to spring controller? Any help is appreciated.
Edit:
I updated JavaScript like this:
var oSettings = $('#propertyTable').dataTable().fnSettings();
var currentPageIndex = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
$('#propertyTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": "${contextPath}/admin/getNextPageData/"+currentPageIndex+"/"+10,
"columns": [
{ "data": "propertyId" },
{ "data": "propertyname" },
{ "data": "propertyType" },
{ "data": "hotProperties" },
{ "data": "address" },
{ "data": "state" },
{ "data": "beds" },
{ "data": "city" },
{ "data": "zipCode" }
]
});
But it's giving me an error:
DataTables warning: table id=propertyTable - Cannot reinitialise DataTable.
DataTables already sends parameters start and length in the request that you can use to calculate page number, see Server-side processing.
If you still need to have the URL structure with the page number, you can use the code below:
"ajax": {
"data": function(){
var info = $('#propertyTable').DataTable().page.info();
$('#propertyTable').DataTable().ajax.url(
"${contextPath}/admin/getNextPageData/"+(info.page + 1)+"/"+10
);
}
},
"Untested"
Edit: Added "retrieve": true in options to retrieve the table instance (v1.10), checked if table exists. Changed fnSettings to setting() for datatable v1.10.
You can try to read from the datatable settings and then from settings read _iDisplayStart and _iDisplayLength , then calculate current page index as follows:
var currentPageIndex = 1;
//Is datatable already initialized?
if ( $.fn.DataTable.isDataTable( '#propertyTable' ) ) {
//Get the current settings and calculate current page index
var oSettings = $('#propertyTable').dataTable({"retrieve": true}).settings();
currentPageIndex = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
}
then in ajax call pass currentPageIndex:
"ajax": "${contextPath}/admin/getNextPageData/"+currentPageIndex +"/"+10,
use this code gives a better result
fnRowCallback: function (nRow, aData, iDisplayIndex) {
var info = table.page.info();
if (
i < info.start ||
i >= info.end
) {
i = info.start;
}
$("td:first", nRow).html(i + 1);
i += 1;
return nRow;
},
Instead reload the datatable using $("YourDataTableId").DataTable().ajax.reload() , we can use below code to send current page number at server side to load data of that page number.
var currentDataTable = $("YourDataTableId").DataTable();
let currentPage = currentDataTable.page() >= 0 ? currentDataTable.page() : 0;
currentDataTable.page(currentPage).draw(false);
along with this code we have to use the below setting in datatable -
$("YourDataTableId").DataTable({
"stateSave": true, // to save the current page
});`
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 :)