I have a datatable that has an edit button on each row. When I click the edit button, a function opens a modal to display the data of the selected record.
Initially, I just want to get the id(which I referred to as PID) of the selected record. However according to my code, I am not sure how to extract the value passed. I kept on getting undefined response.
Please advise on any errors in my code or is there a better way to do this.
Thanks
select: true,
ajax: {
url: "people-grid-data.php",
type: "POST",
},
columnDefs: [{
"targets": [3, 4, 6, 7, 8, 9],
"visible": false,
"searchable": true
},
],
columns: [
{
"width":"2%",
"render": function (data, type, full, meta) {
return "<button type='button' class='btn btn-xs' data-toggle='modal' data-target='#editPersonModal'>Edit </button>";
},
},
{
"data": "PID",
render: getImg
},
{
"data": "PID"
},
{
"data": "personName"
},
{
"data": "PeopleRemarks"
}
],
"order": [
[2, 'asc']
]
});
$('#editPersonModal').on('show.bs.modal', function (data, type, full, meta) {
console.log("Data ID---"+data['PID']);
});
i have a button in my grid , you open your modal with this, using data atributes
render: function (data, type, row) {<a data-info="' + row.IdUser + '" data-toggle="modal" data-target="#modalGridTable" ...
in row.IdUser i have my id. now when i click in $('#modalGridTable').on('show.bs.modal', function (event)...
var button = $(event.relatedTarget);
var id = button.data('info');
var data = Grid.ajax.json().data;
function getDataJson(IdUsuario) {
return data.filter(
function (data) {
return data.IdUser === IdUser;
}
);
}
var result = getDataJson(id);
so you can read this example:
result[0].Phone
Related
I'm displaying all the customer data using DataTables like this:
<script type="text/javascript" src="DataTables/datatables.min.js"></script>
<script>
var theTable = null;
$(document).ready(function() {
theTable = $('#table-customer').DataTable({
"processing": true,
"serverSide": false,
"ordering": true,
"order": [[ 0, 'asc' ]],
"ajax":
{
"url": "http://localhost/myshop/showdata.php",
"type": "GET"
},
"sAjaxDataProp": "data",
"deferRender": true,
"aLengthMenu": [[5, 10, 20, 50],[ 5, 10, 20, 50]],
"columns": [
{ data: "cust_id" },
{ data: "cust_name" },
{ data: "cust_addr" },
{ data: "cust_email" },
{ data: "cust_phone" },
{ data: "cust_photo", sortable: true, render: function (o) { return '<button id="btn1" onclick="displayImage(data)">Show</button>';}
]
});
});
function displayImage(link){
window.alert(link);
}
</script>
All information is displayed properly, except 1 thing: if you click any button on "customer photo" column, instead of showing an alert which shows its URL, nothing happens. Inspecting the page showed me this:
Uncaught ReferenceError: data is not defined
at HTMLButtonElement.onclick (view.html:1)
How to fix this?
The columns.data render function builds a string which is returned:
function (o) { return 'your string here, including data value'; }
You have to (a) concatenate your data variable with the string literals you need; and (b) use the variable name you provided - I will use data instead of o:
function (data) { return 'your string here, including ' + data + ' value'; }
So, if we provide all the possible parameters allowed in the renderer, that becomes:
{
"data": "cust_photo",
"sortable": true,
"render": function(data, type, row, meta) {
return '<button id="btn1" onclick="displayImage(\'' + data + '\')">Show</button>';
}
}
I use \' to ensure the value of the data variable is surrounded in single quotes.
(Note that in your question, the code is also missing a closing }.)
But to avoid potential issues with sorting and filtering, these column data render functions need to account for DataTable's use of orthogonal data.
The type parameter can be used for this:
{
"data": "cust_photo",
"sortable": true,
"render": function(data, type, row, meta) {
if (type === 'display') {
return '<button id="btn1" onclick="displayImage(\'' + data + '\')">Show</button>';
} else {
return data; // type is for sorting or filtering - just use the raw value
}
}
}
I have the following code where I want to use server side to lazy load my data. My goal is to display 10 records per page. The rest of the data should be loaded as and when the user clicks on a particular page.
What's happening now is that the datatable displays all the records at once. Can someone help me fix this issue?
var table = $("#members").DataTable({
"processing": true,
"serverSide": true,
paging: true,
"pagingType": "full_numbers",
"iDisplayLength": "10",
"length": "10",
ajax: {
url: "/api/members",
dataSrc: "",
},
columns: [
{
data: "cardNumber"
},
{
data: "registrationDate",
},
{
data: "fullName",
},
{
data: "address"
},
{
data: "phoneNumber"
},
{
data: "email"
}
]
});
Here's the API code:
// GET /api/members
public IEnumerable<MemberDto> GetMembers(string query = null)
{
var membersQuery = _context.Members.ToList();
if (!String.IsNullOrWhiteSpace(query))
membersQuery = membersQuery.Where(c => c.FullName.Contains(query.ToUpper())).ToList();
var memberDtos = membersQuery.ToList()
.Select(Mapper.Map<Member, MemberDto>);
return memberDtos;
}
Using the jQuery dataTables plugin, I have the following rendering a table (code within each render has been simplified for brievity):
table = $('#index')
.DataTable({
order: [[1, 'desc']],
autoWidth: false,
lengthChange: false,
pageLength: numRows,
ajax: {
url: 'GetTableData/' + application,
dataSrc: ''
},
columns: [
{
data: null,
render: function (data, type, row) {
return '<span></span>';
}
},
{
data: null,
render: function (data, type, row) {
return '<span></span>';
}
},
{
data: null,
render: function (data, type, row) {
return '<span></span>';
}
},
{
data: null,
render: function (data, type, row) {
return '<span></span>';
}
}
]
});
No matter what column number or direction I set the order: [[1,'desc']] to, it always sorts column 1 asc.
Where am I having a disconnect in my code?
I have an on click function storing the row data in the console log
if you click on the first two columns, you'll notice the function returns undefined, however any of the unfrozen columns returns the data object
I know that this has todo with the fact that the fixedcolumns are created in a cloned table, i was wondering if there was any workaround to this?
// Server-side processing with object sourced data
var $table;
$(document).ready(function() {
$table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/ssp/objects.php",
dom: "<'row'<'col-md-6 'l><'col-md-6 pull-right'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
"columns": [
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "start_date" },
{ "data": "salary" }
],
scrollY: "600px",
scrollX: "100%",
scrollCollapse: true,
"pageLength": 5,
lengthMenu: [[5, 10, 25, 50 ], [5, 10, 25, 50]],
order: [[ 1, "asc" ]],
} );
new $.fn.dataTable.FixedColumns( $table, {
leftColumns: 2
} );
$table.on("click", "tr",function(){
var aData = $table.row( this ).data();
console.log( aData);
} );
} );
here is my example code in action
You can use fnGetPosition to get information about row index.
From the manual:
This function is functionally identical to fnGetPosition in
DataTables, taking the same parameter (TH, TD or TR node) and
returning exactly the the same information (data index information).
The difference between the two is that this method takes into account
the fixed columns in the table, so you can pass in nodes from the
master table, or the cloned tables and get the index position for the
data in the main table.
Your code needs to be modified as follows:
var fc = new $.fn.dataTable.FixedColumns( $table, {
leftColumns: 2
});
$table.on("click", "tr", function(){
var aData = $table.row(fc.fnGetPosition(this)).data();
console.log(aData);
});
See this example code for demonstration.
What I want is to get row data when users click on the table's tbody but I keep getting undefined for these datatables functions.
Data comes from a node-mysql module. And for testing purposes, after the table is initialized and data's propertly arrived I've set:
"fnDrawCallback" : function() {
console.log('this:' + this);
console.log('oTable.fnGetData():' + oTable.fnGetData());
console.log('JSON.stringify(oTable.fnGetData():' + JSON.stringify(oTable.fnGetData()));
console.log('JSON.stringify(oTable.fnGetData():' + JSON.stringify(oTable.fnGetData()[0]));
console.log('oTable.fnGetData()[0]:' + oTable.fnGetData()[0]);
},
The result is this:
this:[object Object] tables_offline.js:40
oTable.fnGetData():[object Object],[object Object],[object Object] tables_offline.js:41
JSON.stringify(oTable.fnGetData():[{"id":1,"age":"23","vol":26227,"tlg":4.93,"r":18.15},{"id":2,"age":"13","vol":6378,"tlg":3.97,"r":16.76},{"id":3,"age":"54","vol":131626,"tlg":6.49,"r":11.1}] tables_offline.js:42
JSON.stringify(oTable.fnGetData()[0]:{"id":1,"age":"23","vol":26227,"tlg":4.93,"r":18.15} tables_offline.js:43
oTable.fnGetData()[0]:[object Object]
It's not an array... Maybe this is the weird thing.
I've tried debugging with chrome, setting
$('#myTable').on('click', 'tr', function(){
var oTable = $('#myTable').DataTable();
debugger;
});
And here's a screenshot of what's coming from the variable oTable. I'm not sure but shouldn't I be able to see the functions right there? I can't query something like oTable.fnGetData() 'cause it's undefined.
Let me know if you need something else from my side in order for you to help me.
EDIT
What I want basicaly is to get row data when users click on the table's tbody. I can't get there since oTable = $('#myTable').DataTable(); oTable.fnGetData()' throws undefined.
I'll try to clarify a bit more.
tables_offline.js is the file that loads the datatable, there I define my oTable variable. While searching for help I came across this post (I'm using mData for the columns definition) and I'm not sure if this is the case but it may help.
I make use of fnDrawCallback just for testing oTable in the console, it's not part of the original code.
var oTable = $("#myTable").dataTable({
'fnServerParams': function (aoData) {
aoData.push({ "name": "startDate", "value": startDate });
aoData.push({ "name": "endDate", "value": endDate });
},
'sAjaxSource': '/url',
'sAjaxDataProp': '',
'bProcessing': true,
'sDom':'t',
"aoColumns": [
{ "bVisible": false, "mDataProp": "pcrc_id"},
{ "sWidth": "25%","sTitle": "age", "mDataProp": "pcrc"},
{ "sWidth": "25%","sTitle": "Vol", "mDataProp": "volumen"},
{ "sWidth": "25%","sTitle": "tlg", "mDataProp": "tlg"},
{ "sWidth": "25%","sTitle": "r", "mDataProp": "reitero",
"mRender": function ( data, type, full ) {
return data + '%';
}
}
],
"oLanguage": {
"sUrl": "/javascripts/i18n/dataTables.Spanish.json"
},
"aaSorting": [[ 0, "desc" ]],
"bSort": false,
"bInfo" : false,
"bPaginate": false,
"fnDrawCallback" : function() {
console.log('this:' + this);
console.log('oTable.fnGetData():' + oTable.fnGetData());
console.log('JSON.stringify(oTable.fnGetData():' + JSON.stringify(oTable.fnGetData()));
console.log('JSON.stringify(oTable.fnGetData()[0]:' + JSON.stringify(oTable.fnGetData()[0]));
console.log('oTable.fnGetData()[0]:' + oTable.fnGetData()[0]);
},
"bFilter": false
});
EDIT 2
New screenshot after accesing oTable when a row's clicked. If I dig deep into context I see the data but it's the full thing, not just the row clicked. I'd like to use a function to get clicked row data.
Remove the fnDrawCallback stuff, I think it's distracting you from the actual problem.
Try this:
var oTable = $("#myTable").dataTable({
'fnServerParams': function (aoData) {
aoData.push({ "name": "startDate", "value": startDate });
aoData.push({ "name": "endDate", "value": endDate });
},
'sAjaxSource': '/url',
'sAjaxDataProp': '',
'bProcessing': true,
'sDom':'t',
"aoColumns": [
{ "bVisible": false, "mDataProp": "pcrc_id"},
{ "sWidth": "25%","sTitle": "age", "mDataProp": "pcrc"},
{ "sWidth": "25%","sTitle": "Vol", "mDataProp": "volumen"},
{ "sWidth": "25%","sTitle": "tlg", "mDataProp": "tlg"},
{ "sWidth": "25%","sTitle": "r", "mDataProp": "reitero",
"mRender": function ( data, type, full ) {
return data + '%';
}
}
],
"oLanguage": {
"sUrl": "/javascripts/i18n/dataTables.Spanish.json"
},
"aaSorting": [[ 0, "desc" ]],
"bSort": false,
"bInfo" : false,
"bPaginate": false,
"bFilter": false
});
oTable.$('tr').click( function () {
var data = oTable.fnGetData( this );
console.log(data);
} );
Note that the oTable var is still in scope so you don't need to use var oTable = $('#myTable').DataTable().
This example is copied verbatim from the Datatables API documentation