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 will really appreciated any help. I am trying to fix the display of the text in my html. I use javascript and call the variable and display in html. However the display of the text is not what i desired.
JAVASCRIPT
$(document).ready(function(){
var table= $('#data-table').DataTable({
"ajax" : "employee_data.json",
"columns" : [
{ "data" : "name" },
{ "data" : "gender"},
{ "data" : "designation"},
{ "data" : "image"},
{"defaultContent": '<div style="text-align:center"><button style="width:100%; margin-top: 5px;" class="btn btn-danger" > support </button></div>'}
]
});
$('#data-table tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( "You Click" + " "+data['name'] );
$new="You Click" + " "+data['name'] ;
$images=data['image'];
$names=document.getElementById("name").append = data['name'];
$gender=document.getElementById("gender").append = data['gender'];
$('#img-container').append(data['image']+" " + $names+$gender+" </p>"+"<br>" );
} );
});
Running Result:
Desired Output:
Try to change your style using this unit of measurement to make it responsive to the sizing.
$(document).ready(function() {
var table= $('#data-table').DataTable( {
"ajax" : "employee_data.json",
"columns" : [
{ "data" : "name" },
{ "data" : "gender"},
{ "data" : "designation"},
{ "data" : "image"},
{"defaultContent": '<div style="font-size:15vw;"><button style="width:100%; margin-top: 5px;" class="btn btn-danger"> support </button></div>'}
]
});
How to use java script variable inside blade syntax. (getting error Use of undefined constant buttonID)
The below is the code :
var t = $("#datatable").DataTable({
"order": [[ 1, 'asc' ]],
"ajax": "questions1/get-data",
"deferRender": true,
"processing": true,
sAjaxDataProp: "",
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "description" },
{ "data": "answers.[, ].name" },
{ "data": "campaigns.[, ].name" },
{ "data": "label" },
{
sortable: false,
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
return '#can('view', $question)<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>#endcan
#can('update', $question)<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>#endcan';
}
}
],
});
Use the code below:
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
#can('view', $question)
return '<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>';
#endcan
#can('update', $question)
return '<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>';
#endcan
}
Hi i am using datable server side processing,
$(document).ready(function() {
$("#TABLE").dataTable({
"bProcesing" : true,
"bServerSide" : true,
"bLenthChange" : false,
"iDisplayLength" : 10,
"bSort":false,
"bFilter": true,
"sAjaxSource" : "/easdaspp/abc",
"aoColumns" : [
{
"sTitle" : "Organization Name",
"mData" : "organizationName"
},
{
"sTitle" : "Delete",
"sDefaultContent" : '<a href="abc/{organizationId}" >Delete</a>'
}],
"fnServerData" : function(sSource, aoData, fnCallback) {
$.ajax({
"dataType" : 'json',
"type" : "GET",
"url" : sSource,
"data" : aoData,
"success" : fnCallback
});
},
"sPaginationType" : "full_numbers"
});// dataTable
});
How do i get organizationId value in anchor tag
like this
"sDefaultContent" : '<a href="abc/{organizationId}" >Delete</a>'
should be
<a href="abc/1" >Delete</a>
so on for every rows, the value of url should change according to us
Well I use another method see for yourself
this is the server side script of the old datatables
static function data_output($columns, $data) {
$out = array();
for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array();
for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j];
if ( $aColumns[$i] == "cId" ){
/* Special output formatting for 'cId' column */
$row[] = '
<div id="trigger">
<a target="_blank" title="Click to make Payment" href="viewDetails.php?cId='.$aRow[$aColumns[$i]].'">
<img src="images/icons/color/rupee.png" />
</a>
</div>
';
}
}
}
I got the solution using mRender we can sort this out
{"mData" : "organizationId",
"mRender": function ( data, type, full ) {
return 'Download';
}
I am newbie for DataTables. I want to add button on each row for edit and delete(like below image)
I have tried with code:
Test.cfm
<table id="myDataTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>UserID</th>
<th>Name</th>
<th>UserName</th>
<th>Passowrd</th>
<th>Email</th>
<th>IsActive</th>
<th>Command</th>
</tr>
</thead>
<tbody>
</tbody>
$(document).ready(function () {
var oTable = $('#myDataTable').dataTable({
// "bServerSide": true,
"sAjaxSource": "fetchUserData.cfm",
"bProcessing": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "mData": null },
{ "mData": "Name", "sTitle": "Name" , "sWidth": "20%"},
{ "mData": "UserName", "sTitle": "UserName", "sWidth": "20%" },
{ "mData": "Passowrd","sTitle": "Passowrd", "sWidth": "20%" },
{ "mData": "Email","sTitle": "Email" , "sWidth": "20%"},
{ "mData": "IsActive","sTitle": "IsActive" , "sWidth": "20%" },
{
"mData": null,
"bSortable": false,
"mRender": function (o) { return '<a href=#/' + o.userid + '>' + 'Edit' + '</a>'; }
}
]
});
} );
fetchUserData.cfm
{
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],
[
"2",
"arun singh",
"arun",
"arun",
"arunsingh#test.com",
"0",
""
],
[
"9",
"s s",
"sam3",
"sam3",
"ss#s.com",
"0",
""
],
[
"10",
"sameek mishra",
"sam56",
"sam",
"same#s.com",
"0",
""
],
[
"11",
"narendra kumar",
"narendra",
"nav",
"sa#sa.com",
"1",
""
],
[
"12",
"test test",
"test",
"test",
"test2#test.com",
"1",
""
]
]
}
Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:
fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]
dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered.
I just hardcoded this info to your data. You should get the right values from counts in your server sided script.
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],...
If you have the column names already set in the html part, you don't need to add sTitle.
The mRender Function takes three parameters:
data = The data for this cell, as defined in mData
type = The datatype (can be ignored mostly)
full = The full data array for this row.
So your mRender function should look like this:
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
}
Find a working Plunker here
var table =$('#example').DataTable( {
data: yourdata ,
columns: [
{ data: "id" },
{ data: "name" },
{ data: "parent" },
{ data: "date" },
{data: "id" , render : function ( data, type, row, meta ) {
return type === 'display' ?
'</i>' :
data;
}},
],
}
}
take a look here... this was very helpfull to me
https://datatables.net/examples/ajax/null_data_source.html
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
$('#example tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] +"'s salary is: "+ data[ 5 ] );
} );
} );
I contribute with my settings for buttons: view, edit and delete.
The last column has data: null
At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.
//...
columns: [
{ title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
{ title: "Id", "data": "id", defaultContent: '', "visible":false },
{ title: "Nombre", "data": "nombre" },
{ title: "Apellido", "data": "apellido" },
{ title: "Documento", "data": "tipo_documento.siglas" },
{ title: "Numero", "data": "numero_documento" },
{ title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
{ title: "Teléfono", "data": "telefono1" },
{ title: "Email", "data": "email1" }
, { title: "", "data": null }
],
columnDefs: [
{
"searchable": false,
"orderable": false,
"targets": 0
},
{
width: '3%',
targets: 0 //la primer columna tendra una anchura del 20% de la tabla
},
{
targets: -1, //-1 es la ultima columna y 0 la primera
data: null,
defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button> <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
},
{ orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
],
//...
enter image description here
Take a Look.
$(document).ready(function () {
$('#datatable').DataTable({
columns: [
{ 'data': 'ID' },
{ 'data': 'AuthorName' },
{ 'data': 'TotalBook' },
{ 'data': 'DateofBirth' },
{ 'data': 'OccupationEN' },
{ 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
],
bServerSide: true,
sAjaxSource: 'EmployeeDataHandler.ashx'
});
});
my recipe:
datatable declaration:
defaultContent: "<button type='button'....
events:
$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }
well, i just added button in data.
For Example,
i should code like this:
$(target).DataTable().row.add(message).draw()
And, in message, i added button like this : [blah, blah ... "<button>Click!</button>"] and.. it works!