Related
Hello I am fairly new to datatable and I would like to seek help in retrieving the User ID when I click the button and that would trigger another ajax call where it will do a POST method but I am unsure how it can be done within the script tag. Is this the right method to implement the data and the button? I really need some advice on this.
Here is my code :
<script>
uId = sessionStorage.getItem('uId')
username = sessionStorage.getItem('username')
var userListTable = $('#userListTable').dataTable({
'ajax': {
"type" : "GET",
"url" : "http://localhost:8080/Test-war/webresources/users/" + uId + "/retrieveUserList",
"dataSrc": ""
},
'columns': [
{title : "User ID", "data" : "id"},
{title : "Username", "data" : "username"},
{title : "Gender", "data" : "gender"},
{title : "Email", "data" : "email"},
{title : "Contact", "data" : "contact"},
{title : "Created", "data" : "created", "render" : function(data) {
var date = new Date(data);
var month = date.getMonth() + 1;
return (month.toString().length > 1 ? month : "0"
+ month) + "/" + date.getDate() + "/" + date.getFullYear();
}},
{title : "Follow User", "defaultContent" : '<button onclick="followUser()">Follow User</button>'},
{title : "Unfollow User", "defaultContent" : '<button onclick="unfollowUser()">Unfollow User</button>'},
]
});
</script>
From here I am using a function followerUser() but I have no idea how am I able to get the tId of the row that the button was clicked at.
function followUser() {
var tId =
$.ajax({
type: "POST",
url: "http://localhost:8080/Test-war/webresources/users/" + tId + "/followUser",
data: body,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, xhr)
{
alert("You have successful followed user")
window.location.href = "viewUserList.html";
console.log(data)
console.log(textStatus)
},
error: function(xhr, error, errorType) {
alert("Error following user...")
}
});
Here is the image of the datatable :
You can use something like below code. you can use datatable API to fetch row data.
var dataSet = [
{'engine':'Webkit','browser':'Safari 1.2','platform':'OSX.3','version':'125.5','grade':'A'},
{'engine':'Other browsers','browser':'All others','platform':'-','version':'-','grade':'U'}
];
$(document).ready(function() {
$('#demo').html('<table class="display" id="example"></table>');
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "sortable" : false, "data": null, "defaultContent": "<button>Select</button>", "title" : "Choose"
},
{ "title": "Engine", "data": "engine" },
{ "title": "Browser", "data": "browser" },
{ "title": "Platform", "data": "platform" },
{ "title": "Version", "data": "version", "class": "center" },
{ "title": "Grade", "data": "grade", "class": "center" },
{ "defaultContent": true, "data": "existing", "visible": false }
],
initComplete: function(oSettings, json) {
console.log('drawing complete');
if (oSettings.fnRecordsTotal() > 1) {
$('#example').DataTable().row.add({
'engine' : 'Presto',
'browser' : 'Opera 7.5',
'platform' : 'Win 95+ / OSX.2+',
'version' : '-',
'grade' : 'A',
'existing' : false
}).draw();
}
}
} );
$('#example tbody').on('click', 'button', function(e) {
var data = $('#example')
.DataTable()
.row( $(this).parents('tr') )
.data();
console.log(data.version);// obj.columnname you can use data.id in you case to fetch User id
});
});
here is working example
I'm trying to use datatables to display a list of records in two different pages.
Problem is the first datatable works while the second one (that's a perfect clone of the first) doesn't...
The issue is related to $.fn.DataTable: in the first case it exists so the script goes on filling the datatable while in the second case it is undefined.
The "big" problem here is that both the datatables are perfectly the same. What changes are the ids and the content...
These are the two scripts I'm using to populate the datatables:
transactionsHistoryInit : function($) {
var datatable = $('#transactions-history-table');
if (datatable.length > 0 && typeof $.fn.DataTable !== "undefined") {
datatable.DataTable({
"responsive" : true,
"searching" : false,
"processing" : true,
"serverSide" : true,
"pageLength" : 20,
"lengthChange" : false,
"stateSave" : true,
"pagingType" : "full_numbers",
"info" : false,
"columnDefs" : [ {
"orderable" : false,
"targets" : [ 1, 2, 3, 4 ]
} ],
"ajax" : {
"url" : siteData.ajaxurl + "?action=transactions_history",
"type" : 'POST'
},
"language" : {
"url" : siteData.ajaxurl
+ "?action=datatable_internazionalization"
}
});
transactionStartDate.datetimepicker({
"locale" : transactionStartDate.data("locale")
});
transactionEndDate.datetimepicker({
"locale" : transactionEndDate.data("locale"),
"defaultDate" : new Date()
});
transactionStartDate.add(transactionEndDate).on("dp.change",
function(e) {
datatable.draw();
});
}
},
bankToBankAccountChoice : function($) {
var datatable = $('#bank-account-table');
if (datatable.length > 0 && typeof $.fn.DataTable !== "undefined") {
datatable.DataTable({
"responsive" : true,
"searching" : false,
"processing" : true,
"serverSide" : true,
"pageLength" : 10,
"lengthChange" : false,
"stateSave" : true,
"pagingType" : "full_numbers",
"info" : false,
"ajax" : {
"url" : siteData.ajaxurl
+ "?action=bank_to_bank_account_choice",
"type" : 'POST'
},
"language" : {
"url" : siteData.ajaxurl
+ "?action=datatable_internazionalization"
}
});
}
}
I was also getting $.fn.dataTable as undefined
In my case, I was loading jquery multiple times. Jquery must be loaded only once.
I'm building a nested table with DataTable.
The table is built from a JSON string str that I get from an Ajax call.
str before JSON.parse:
"[ {\r\n \"ente\" : \"Roma\",\r\n \"cup\" : \"ABCDE3593CXXE\",\r\n \"decretoImpegno\" : \"decreto singolo\",\r\n \"dataDecretoImpegno\" : 61415276400000,\r\n \"importoImpegno\" : 56000,\r\n \"finanziatoMiur\" : 343434,\r\n \"importoPagato\" : 55656,\r\n \"importoInPagamento\" : 9999,\r\n \"details\" : [ {\r\n \"progressivoPagamento\" : 22,\r\n \"dataDecreto\" : 61415276400000,\r\n \"numeroDecretoPagamento\" : \"numero dec pag\",\r\n \"tipoPagamento\" : \"tipo pag\",\r\n \"importoInPagamento\" : 45,\r\n \"notaDecreto\" : \"nota dec\"\r\n }, {\r\n \"progressivoPagamento\" : 22,\r\n \"dataDecreto\" : 61415276400000,\r\n \"numeroDecretoPagamento\" : \"numero dec pag\",\r\n \"tipoPagamento\" : \"tipo pag\",\r\n \"importoInPagamento\" : 45,\r\n \"notaDecreto\" : \"nota dec\"\r\n } ]\r\n}, {\r\n \"ente\" : \"Roma\",\r\n \"cup\" : \"ABCDE3593CXXE\",\r\n \"decretoImpegno\" : \"decreto singolo\",\r\n \"dataDecretoImpegno\" : 61415276400000,\r\n \"importoImpegno\" : 56000,\r\n \"finanziatoMiur\" : 343434,\r\n \"importoPagato\" : 55656,\r\n \"importoInPagamento\" : 9999,\r\n \"details\" : [ {\r\n \"progressivoPagamento\" : 22,\r\n \"dataDecreto\" : 61415276400000,\r\n \"numeroDecretoPagamento\" : \"numero dec pag\",\r\n \"tipoPagamento\" : \"tipo pag\",\r\n \"importoInPagamento\" : 45,\r\n \"notaDecreto\" : \"nota dec\"\r\n }, {\r\n \"progressivoPagamento\" : 22,\r\n \"dataDecreto\" : 61415276400000,\r\n \"numeroDecretoPagamento\" : \"numero dec pag\",\r\n \"tipoPagamento\" : \"tipo pag\",\r\n \"importoInPagamento\" : 45,\r\n \"notaDecreto\" : \"nota dec\"\r\n } ]\r\n} ]"
After that, I parse this string to JSON: str = JSON.parse(str).
Then, I pass the str to DataTable:
var oTable = $('#exampleTable').dataTable({
"bJQueryUI": true,
"aaData": str,
...
But, I get an error:
DataTables warning: table id=exampleTable - Requested unknown parameter 'ente' for row 0. For more information about this error, please see http://datatables.net/tn/4
The strange thing happen when, before to parse the str string:
(1)I display it with console.log(str); in my web console.
(2)I copy the result of console.log into a js variable.
var res = [ { //this JSON is exactly what I get from Ajax, the same I parsed..
"ente" : "Roma",
"cup" : "ABCDE3593CXXE",
"decretoImpegno" : "decreto singolo",
"dataDecretoImpegno" : 61415276400000,
"importoImpegno" : 56000,
"finanziatoMiur" : 343434,
"importoPagato" : 55656,
"importoInPagamento" : 9999,
"details" : [ {
"progressivoPagamento" : 22,
"dataDecreto" : 61415276400000,
"numeroDecretoPagamento" : "numero dec pag",
"tipoPagamento" : "tipo pag",
"importoInPagamento" : 45,
"notaDecreto" : "nota dec"
}],
"importoDaPagare" : 277779
}, {
"ente" : "Roma",
"cup" : "ABCDE3593CXXE",
"decretoImpegno" : "decreto singolo",
"dataDecretoImpegno" : 61415276400000,
"importoImpegno" : 56000,
"finanziatoMiur" : 343434,
"importoPagato" : 55656,
"importoInPagamento" : 9999,
"details" : [ {
"progressivoPagamento" : 22,
"dataDecreto" : 61415276400000,
"numeroDecretoPagamento" : "numero dec pag",
"tipoPagamento" : "tipo pag",
"importoInPagamento" : 45,
"notaDecreto" : "nota dec"
} ],
"importoDaPagare" : 277779
} ];
(3) I pass this variable to DataTable (without parse it) and works!!
var oTable = $('#exampleTable').dataTable({
"bJQueryUI": true,
"aaData": res,
...
How it's possible?
Datatable.js
detailsTableHtml = $("#detailsTable").html();
//Insert a 'details' column to the table
var nCloneTh = document.createElement('th');
var nCloneTd = document.createElement('td');
nCloneTd.innerHTML = '<img src="http://i.imgur.com/SD7Dz.png">';
nCloneTd.className = "center";
$('#exampleTable thead tr').each(function () {
this.insertBefore(nCloneTh, this.childNodes[0]);
});
$('#exampleTable tbody tr').each(function () {
this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
});
//Initialse DataTables, with no sorting on the 'details' column
var oTable = $('#exampleTable').dataTable({
"bJQueryUI": true,
"aaData": res,
"bPaginate": true,
"aoColumns": [
{
"mDataProp": null,
"sClass": "control center",
"sDefaultContent": '<img src="http://i.imgur.com/SD7Dz.png">'
},
{ "mDataProp": "ente" },
{ "mDataProp": "cup" },
{ "mDataProp": "decretoImpegno" },
{ "mDataProp": "dataDecretoImpegno" },
{ "mDataProp": "importoImpegno" },
{ "mDataProp": "finanziatoMiur" },
{ "mDataProp": "importoPagato" },
{ "mDataProp": "importoInPagamento" }
],
"oLanguage": {
"sInfo": "_TOTAL_ entries"
},
"aaSorting": [[1, 'asc']]
});
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('#exampleTable tbody td img').on('click', function () {
var nTr = $(this).parents('tr')[0];
var nTds = this;
if (oTable.fnIsOpen(nTr)) {
/* This row is already open - close it */
this.src = "http://i.imgur.com/SD7Dz.png";
oTable.fnClose(nTr);
}
else {
/* Open this row */
var rowIndex = oTable.fnGetPosition( $(nTds).closest('tr')[0] );
var detailsRowData = res[rowIndex].details;
this.src = "http://i.imgur.com/d4ICC.png";
oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, detailsTableHtml), 'detail');
oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
"bJQueryUI": true,
"bFilter": true,
"aaData": detailsRowData,
"bSort" : true, // disables sorting
"aoColumns": [
{ "mDataProp": "progressivoPagamento" },
{ "mDataProp": "dataDecreto" },
{ "mDataProp": "numeroDecretoPagamento" },
{ "mDataProp": "tipoPagamento" },
{ "mDataProp": "importoInPagamento" },
{ "mDataProp": "notaDecreto" }
],
"bPaginate": true,
"oLanguage": {
"sInfo": "_TOTAL_ entries"
}/*,
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var imgLink = aData['pic'];
var imgTag = '<img width="100px" src="' + imgLink + '"/>';
$('td:eq(0)', nRow).html(imgTag);
return nRow;
}*/
});
iTableCounter = iTableCounter + 1;
}
});
SOLUTION: I miss to add dataType: 'json' into the aJax call...
How do I reload datatables with the new ajax functionality?
I think it's a problem of scope.
function load_table(tableName,src)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
'bServerSide' : true,
'responsive' : true,
'sAjaxSource' : src,
'fnServerData' : function(sSource, aoData, fnCallback)
{
$.ajax({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
},
});
}
Try to reload it from a different data source:
$("input[type="button"]").on('click',function()
{
oTable.ajax.url( 'newsource' ).load();
alert( 'Data source: '+oTable.ajax.url() );
});
Alert outputs : src : newsource
Browser loads table from src: oldsource
I've had the same issue to anyone who runs into this problem in the future here is the solution:
To accomplish reloading of data from a different source:
refer to the DOM table element NOT the DataTable object or you will get a reinitilization error:
step 1: clear data :
$('#your_table_name').DataTable().clear();
step 2: Destroy the DataTable object
$('#your_table_name').DataTable().destroy();
if you're using child rows this is very important remove the click listener
$( "#your_table_name tbody" )
.off( "click", "td.details-control");
Reinit DataTables:
loadTable('newsource','your_table_name')
and your loadTable function
function loadTable(src,tableName)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
'bServerSide' : true,
'responsive' : true,
"sDom": '<"toolbar"lfr>tip<"F">R',
'sAjaxSource' : src,
});
//initchildrows()
}
Yes, this seems to be a scope problem. You assign the dataTables instance to a local variable :
function load_table(tableName,src)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
...
assign it to a global variable instead :
var oTable;
function load_table(tableName,src)
{
oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
...
If it still not works - but it should, you are using oTable.ajax.url(<src>).load() just right - then simply reinitialise the table with the destroy : true option :
var oTable;
function load_table(tableName,src)
{
oTable = $('#'+tableName).DataTable({
destroy : true,
'bProcessing' : true,
...
and call load_table from the event :
$("input[type='button']").on('click',function()
{
load_table('tableName', 'newsource');
});
Thanks,Here is my solution,it is not perfect,must send twice url,thanks to this author: How do I modify ajax url of a query datatable? eg: if you If you initialize datatable like this:
var datatables_options = {
"aLengthMenu" : [ [ 5, 10, 50, 100,500, -1 ],[ 5, 10, 50, 100,500, "All" ] ],
"iDisplayLength" : 5,
"sDom": 'T<"clear">rt<"float_left"i><"float_right_nexpage"p><"float_right_display"l>',
<'float_right_nexpage'p> <'float_right_display'l>>",
"bSort" : false,
"bProcessing" : false,
"bServerSide" : true,
"bStateSave" : true,
"bDestroy" : true,
"bDeferRender":true,
"bJQueryUI" : false,
"sScrollX" : "100%",
"bStateSave":true,
"language" : oLanguageData,
"aoColumns" : aoColumnsData,
"fnDrawCallback" : function() {
//Checkbox status updates
$("#uniform-check-all").removeClass("checker");
$("span").removeClass("checked");
$("span #check-all").attr("checked",false);
$.uniform.update();
},
"fnRowCallback" : function(nRow, aData,
iDataIndex) {
},
"sAjaxSource" : "wageQuery.action?wageDate="
+ date,
"fnServerData" : function(sSource, aoData,
fnCallback) {
$.ajax({
"type" : 'post',
"async":false,
"url" : sSource,
"dataType" : "json",
"data" : aoData,
"success" : function(resp) {
fnCallback(resp);
}
});
},
"fixedColumns": {
"iLeftColumns" : 4,
"sHeightMatch" : "auto"
},
};
import: if you want to reload new url(action),here is the solution: first step: Initialize table variables at the JSP file,like this:
<script type="text/javascript">
var wageNowTable;//Table global variables, do not put in the ready function, otherwise it is not a global variable
</script>
second step: Add the following code to the JS file,like this:
$("#wages-query")
.click(
function() {
var datatables_options = {
"aLengthMenu" : [ [ 5, 10, 50, 100,500, -1 ],[ 5, 10, 50, 100,500, "All" ] ],
"iDisplayLength" : 5,
//The following SDOM, 1.9 version will not show up
"sDom": 'T<"clear">rt<"float_left"i><"float_right_nexpage"p><"float_right_display"l>',
//"sDom" : "<r>t<'float_left'i><'float_right_nexpage'p><'float_right_display'l>>",
"bSort" : false,
"bProcessing" : false,
"bServerSide" : true,
"bStateSave" : true,
"bDestroy" : true,
"bDeferRender":true,
"bJQueryUI" : false,
"sScrollX" : "100%",
"bStateSave":true,
"language" : oLanguageData,
// "aaData" : data,
"aoColumns" : aoColumnsData,
"fnRowCallback" : function(nRow, aData,
iDataIndex) {
},
"sAjaxSource" : "wageQuery.action?wageDate="
+ date,
"fnServerData" : function(sSource, aoData,
fnCallback) {
$.ajax({
"type" : 'post',
"async":false,
"url" : sSource,
"dataType" : "json",
"data" : aoData,
"success" : function(resp) {
fnCallback(resp);
}
});
},
"fixedColumns": {
"iLeftColumns" : 4,
"sHeightMatch" : "auto"
},
};
//Determine whether the table has been an instance, there is no instance, has been a direct update, load the corresponding URL
if (typeof(wageNowTable) == "undefined") {
wageNowTable = $('#sample_1').dataTable(datatables_options);
}else{
var oSettings = wageNowTable.fnSettings();
oSettings.sAjaxSource = "wageQuery.action?wageDate="
+ date;
wageNowTable.fnDraw(false);//Don't jump to the first page, the page number and the reserved page displays the number of
wageNowTable.fnDraw(false);//
}
//Important point: listen to the state of the check box, the important need to use the form of on, the direct click can not change the state
$('.DTFC_LeftHeadWrapper div').on('click','input' ,function () {
$("#uniform-check-all").removeClass("checker");
$("span").removeClass("checked");
var val = $(this).prop("checked");
$("input[type='checkbox']", ".DTFC_LeftHeadWrapper").attr("checked", val);
$("#check-all").attr("checked", val);
if (val) {
$(".checkboxes").each(function(index){
$(this).attr("checked", val);
});
} else {
$(".checkboxes").each(function(index){
$(this).attr("checked", val);
});
}
} );
});
Determine whether the table has been an instance, there is no instance, has been a direct update, load the new URL:
if (typeof(wageNowTable) == "undefined") {
wageNowTable = $('#sample_1').dataTable(datatables_options);
}else{
var oSettings = wageNowTable.fnSettings();
oSettings.sAjaxSource = "wageQuery.action?wageDate="
+ date;
//need twice fndraw
wageNowTable.fnDraw(false);
wageNowTable.fnDraw(false);
}
Here is my code
oTable = $('#userlisttable')
.dataTable(
{
"serverSide" : false,
"ajax" : {
"url" : context + "user/get",
},
"columns" : [ {
"data" : "username"
}, {
"data" : "userpassword"
}, {
"data" : "usertype"
}, {
"data" : "firstname"
}, {
"data" : "lastname"
}, {
"data" : "emailaddress"
}, {
"data" : "isactive"
}, ],
"columnDefs" : [ {
"targets" : "7",
"data" : "userId",
"render" : function(data, type,
full, meta) {
return '<a href="#" id="row'
+ data
+ '" class="btn btn-success" onclick="callModal(id)"><i class="glyphicon glyphicon-edit icon-white"></i>EDIT</a> <a href="#" id="row'
+ data
+ '" class="btn btn-danger" onclick="callDeleteModal(id)"><i class="glyphicon glyphicon-trash icon-white"></i>Deactivate</a>';
}
} ],
"sDom" : 'T<"clear">lfrtip',
"oTableTools" : {
"sRowSelect" : "single",
"sSwfPath" : "../../resources/swf/copy_csv_xls_pdf.swf",
"aButtons": [
"csv"
]
}
});
server returns following Json
[{"password":"password","username":"user","lastAccess":1408089626000,"creationDate":1408089626000,"userId":1,"lastName":"reddy","isActive":"y","firstName":"manjari","email":"man#gmail.com","isLdap":"y","ldapQuery":"query","accessType":"any","usertype":"admin"}]
but data is not dislpled in datatable.
From the doc on the ajax option (scroll down to the examples) :
Get JSON data from a file via Ajax, using dataSrc to read data from a plain array rather than an array in an object:
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"dataSrc": ""
}
} );