How Parsing javascript vars to PHP in Datatable - datatables

I'm new in datatables and sorry for my bad english.
I really need your help to help solve my problem.
So, my code is all in one page :
$( function () {
var oTable;
function fnFormatDetails( nTr ) {
var aData = oTable.fnGetData(nTr);
sOut = "<?php foreach($this->m_rumah_sakit->getStyleAndCount(280)->result() as $style){
echo $style->keterangan; ?>
<br /> 1. Yes : ( <i><?php echo ($style->yes)?$style->yes:'0'; ?> Ulasan </i>)
<br /> 2. No : ( <i><?php echo ($style->no)?$style->no:'0'; ?> Ulasan</i> )
<br /> 3. Not Sure : ( <i><?php echo ($style->not_sure)?$style->not_sure:'0'; ?> Ulasan</i> ) <br /><?php } ?>";
return sOut;
}
$(document).ready ( function() {
oTable = $('#tSortable').dataTable({
"bProcessing": true,
"bServerSide": true,
"aaSorting": [[1,'asc']],
"oLanguage": {"sProcessing": "<img src=" + vars.loader + ">"},
//"sAjaxSource": "../details_col.php",
"sAjaxSource" : base + "cms-ajax-data",
"fnServerParams" : function ( aoData ) {
aoData.push(
{ "name": "p", "value" : "" },
{ "name": "hRating", "value" : "hospital" }
,{ "name": "c", "value" : vars.column }
,{ "name": "iC", "value" : vars.indexColumn }
,{ "name": "t", "value" : vars.table }
,{ "name": "w", "value" : vars.where }
,{ "name": "imp", "value" : vars.implode }
);
},
"aoColumnDefs": [{"bSortable":false,"bSearchable":false, "sClass": "hidden", "aTargets":[1]}]
});
$('#tSortable tbody td img').live('click',function(){
var nTr = this.parentNode.parentNode;
if(this.src.match('details_close')){
this.src = "..//details_open.png";
oTable.fnClose(nTr);
}else
this.src = "../details_close.png";
oTable.fnOpen(nTr,fnFormatDetails(nTr),'details');
}
});
});
And all works like charms! the only problem is : how i can get variable aData[2] in PHP script?
I mean, how to call it like this in my PHP code :
foreach($this->m_rumah_sakit->getStyleAndCount("+aData[2]+")->result();
Hope you understand what I mean. Thanks for any advise.

Related

DataTable doesn't show data

I am trying to use Datatable and I have an issue with Datatable populating data in my .net core project.When the page is loaded, DataTable records are empty.According to the picture below:
Controller:
public IActionResult ShowCategory()
{
return View();
}
public IActionResult CategoryList()
{
try
{
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
// Skiping number of Rows count
var start = Request.Form["start"].FirstOrDefault();
// Paging Length 10,20
var length = Request.Form["length"].FirstOrDefault();
// Sort Column Name
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
// Sort Column Direction ( asc ,desc)
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
// Search Value from (Search box)
var searchValue = Request.Form["search[value]"].FirstOrDefault()
var data = _categoryRepository.GetCategories();
return Json(new { draw = 1, recordsFiltered = 4, recordsTotal = 4, data = data });
}
catch(Exception ex)
{
throw;
}
}
Due to a problem with the code, I have now passed the draw and ... to View as a hardcode.
GetCategories() method:
public List<CategoryViewModel> GetCategories()
{
var query = _CategoryRepo.GetAll();
var q = query.Select(s => new CategoryViewModel
{
Id = s.Id,
CaregoryParentId = s.CaregoryParentId,
Priority = s.Priority,
Title = s.Title
}).ToList();
return q;
}
view:
#{
Layout = null;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="~/css/admin/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="example" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>CaregoryParentId</th>
<th>Priority</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<script>
$(document).ready(function ()
{
$("#example").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/Admin/Category/CategoryList",
"type": "POST",
"datatype": "json"
//"success": function (data) {
// alert(JSON.stringify(data));
//}
},
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false
}],
{ "data": "Id", "name": "Id", "autoWidth": true },
{ "data": "Title", "name": "Title", "autoWidth": true },
{ "data": "CaregoryParentId", "name": "CaregoryParentId", "autoWidth": true },
{ "data": "Priority", "name": "Priority", "autoWidth": true },
{
"render": function (data, type, full, meta)
{ return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }
},
{
data: null, render: function (data, type, row)
{
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";
}
},
]
});
});
function DeleteData(CustomerID)
{
if (confirm("Are you sure you want to delete ...?"))
{
Delete(CustomerID);
}
else
{
return false;
}
}
function Delete(CustomerID)
{
var url = '#Url.Content("~/")' + "DemoGrid/Delete";
$.post(url, { ID: CustomerID }, function (data)
{
if (data)
{
oTable = $('#example').DataTable();
oTable.draw();
}
else
{
alert("Something Went Wrong!");
}
});
}
</script>
when I debug, I receive data in Ajax success function, but it is not shown in the table.
can anybody help me?
Thanks a lot
when I debug, I receive data in Ajax success function, but it is not
shown in the table.
From the result above we can see, server return serializes JSON with camel case names by default.
Id => id
Title => title
CaregoryParentId => caregoryParentId
Priority => priority
But in your script, "data" is set as "Id".
Solution
Use the codes below to avoid camel case names by default.
services.AddControllersWithViews().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
Codes of JS
$(document).ready(function ()
{
$("#example").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/Admin/Category/CategoryList",
"type": "POST",
"datatype": "json",
//"success": function (data) {
// alert(JSON.stringify(data));
//}
},
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false
}],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true },
{ "data": "Title", "name": "Title", "autoWidth": true },
{ "data": "CaregoryParentId", "name": "CaregoryParentId", "autoWidth": true },
{ "data": "Priority", "name": "Priority", "autoWidth": true },
{
"render": function (data, type, full, meta) { return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }
},
{
data: null, render: function (data, type, row) {
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";
}
}
]
});
});
Test of result

How to show a tooltip on a datatable cell and how to fill data in tabular format in the tooltip?

Below is my datatable creation code. on the 'Show Details' column I need to show a tooltip. I have written below for that cell but I am facing below two problems.
Value from render function is overrding my cellĀ“s value. So 'Show
Details' is getting replaced by value from render function.
Values which I am getting from ajaxSource, I need to show in
tabular format in the tooltip. Below is my code:
Code
function testDataTable() {
var columnIndex=$('#columnIndex').val();
var sortBy=$('#sortBy').val();
var resultPerPage=$('#resultPerPage').val();
if(columnIndex=='' || sortBy==''){
resultPerPage=20;
columnIndex=0;
sortBy="desc";
}
testDataTable= $('#testDataTable').dataTable({
"bProcesing" : true,
"bServerSide" : true,
"sort" : "position",
"destroy" : true,
"processing" : true,
"bFilter" : false,
"bLenthChange" : false,
"iDisplayLength" : 4,
"sAjaxSource" : "getRulesDetails.act",
"order" : [ [ columnIndex, sortBy ] ],
"pageLength" : Number(resultPerPage),
"columnDefs": [
{ "orderable": false, "targets":[3, 4] }
],
"aoColumns" : [
{
"mData" : "crId"
},
{
"mData" : "crNo"
},
{
"mData" : "sbNo"
},
{
"mData" : "matchType"
},
{
"mData" : null,
"defaultContent": 'Show Details',
"render": function (data, type, full, meta) {
return '<span data-toggle="tooltip" title="Testing"></span>';
}
}
],
}
} );
}

Filter on nested (recursive) data ( Vue 2 )

Here is an example of my JSON data :
"data":[
{
"id":01,
"name":"test",
"parent_id":null,
"children":[
{
"id":15,
"name":"subChild",
"parent_id":21,
"children":[
{
"id":148,
"name":"subSubChild",
"parent_id":22,
"children":[
....
]
}
]
}
]
},
I would like to filter this level by level. I have made this method :
computed: {
filteredData: function () {
let filterData = this.filter.toLowerCase()
return _.pickBy(this.data, (value, key) => {
return _.startsWith(value.name.toLowerCase(), filterData)
})
},
This work for only the first "level" and I tried several solutions but none worked for children.
So, I would like to be able to filter by several levels.
If you have an idea!
Thank you
A recursive function could come in handy for this particular purpose.
Try the following approach, and for better view, click on Full page link next to the Run code snippet button down below.
new Vue({
el: '#app',
data() {
return {
filter: '',
maintainStructure: false,
data: [{
"id": 01,
"name": "test",
"parent_id": null,
"children": [{
"id": 15,
"name": "subChild",
"parent_id": 21,
"children": [
{
"id": 148,
"name": "subSubChild",
"parent_id": 22,
"children": []
},
{
"id": 150,
"name": "subSubChild3",
"parent_id": 24,
"children": []
}
]
}]
}]
}
},
methods: {
$_find(items, predicate) {
let matches = [];
for (let item of items) {
if (predicate(item)) {
matches.push(item);
}
else if (item.children.length) {
let subMatches = this.$_find(item.children, predicate);
if (subMatches.length) {
if (this.maintainStructure) {
matches.push({
...item,
children: subMatches
});
}
else {
matches.push(subMatches);
}
}
}
}
return matches;
},
filterBy(item) {
return item.name.toLowerCase().startsWith(this.filter.toLowerCase());
}
},
computed: {
filteredData() {
return this.$_find(this.data, this.filterBy);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<label>Filter by <code>item.name</code>:</label>
<input v-model.trim="filter" placeholder="e.g. subsub" />
</div>
<div>
<label>
<input type="checkbox" v-model="maintainStructure" /> Maintain structure
</label>
</div>
<hr />
<pre>{{filteredData}}</pre>
</div>
Note that I'm prefixing the function with $_ to sort of mark it as private function (as recommended in this Style Guide) since we're not going to invoke it anywhere else.

Wanting to use DataTables to nest a table within a table...within a table...can it be done?

I just started using dataTables so I'm hoping this will be a learning opportunity.
I work for a school system and trying to develop a table that will show a student's grades from year to year. I want an administrator to be able to click on any year, and the table will expand to show a child table with the student's GPA for each term (6 terms per school year). Finally, I want the administrator to be able to click on any term and show a child table for actual classes the student took that term and their grade.
I'm able to successfully get the term table to show, but I'm having no luck getting the course table to show. I'm hoping it's not a case of "you can't nest a table within a table within a table", but I can't figure out how to make it stick, although I'm pretty sure it has to do with the "details-control" class...
Here is a link to a fiddle I put together showing what I have...any help finishing it up would be greatly appreciated!!
fiddle me this
var iTermGPACounter = 1;
$(document).ready(function() {
loadDetailsByCourse();
});
function loadDetailsByCourse() {
var table = $('#msGrades').DataTable({
data: [{
"__type": "DMC.WebServices.detailGPA",
"schoolYearLabel": "14-15",
"schoolLevel": "02",
"location": "Highland",
"grade": "7",
"gpaValue": "3.119",
"termGPA": [{
"term": "1",
"gpaValue": "3.857",
"termCourseGrades": [{
"courseNo": "38929712",
"sectionNo": "200",
"courseName": "HEALTH 2",
"letterGrade": "A+",
"department": "EL"
}, {
"courseNo": "32320711",
"sectionNo": "10",
"courseName": "LANG ARTS 2",
"letterGrade": "A+",
"department": "EL"
}, {
"courseNo": "32720711",
"sectionNo": "10",
"courseName": "MATH 2",
"letterGrade": "B",
"department": "MA"
}]
}, {
"term": "2",
"gpaValue": "3.714",
"termCourseGrades": [{
"courseNo": "38929712",
"sectionNo": "200",
"courseName": "HEALTH 2",
"letterGrade": "A",
"department": "EL"
}, {
"courseNo": "32320711",
"sectionNo": "10",
"courseName": "LANG ARTS 2",
"letterGrade": "A",
"department": "EL"
}, {
"courseNo": "32720711",
"sectionNo": "10",
"courseName": "MATH 2",
"letterGrade": "A-",
"department": "MA"
}]
}]
}, {
"__type": "DMC.WebServices.detailGPA",
"schoolYearLabel": "15-16",
"schoolLevel": "02",
"location": "Highland",
"grade": "8",
"gpaValue": "3.123",
"termGPA": [{
"term": "1",
"gpaValue": "3.143",
"termCourseGrades": [{
"courseNo": "32320711",
"sectionNo": "12",
"courseName": "LANG ARTS 2",
"letterGrade": "A",
"department": "EL"
}, {
"courseNo": "32720711",
"sectionNo": "12",
"courseName": "MATH 2",
"letterGrade": "D",
"department": "MA"
}]
}]
}],
paging: false,
columns: [{
className: 'details-control',
orderable: false,
data: null,
defaultContent: '<img src="http://i.imgur.com/SD7Dz.png">'
}, {
data: "schoolYearLabel"
}, {
data: "grade"
}, {
data: "location"
}, {
data: "gpaValue"
}],
order: [
[1, 'asc']
]
});
// Add event listener for opening and closing details
$('#msGrades tbody').on('click', 'td.details-control', function() {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(formatTermGPA(iTermGPACounter)).show();
tr.addClass('shown');
var oInnerTable = $('#termGPA_' + iTermGPACounter).dataTable({
data: row.data().termGPA,
paging: false,
searching: false,
columns: [{
className: 'details-control',
orderable: false,
data: null,
defaultContent: '<img src="http://i.imgur.com/SD7Dz.png">'
}, {
data: "term"
}, {
data: "gpaValue"
}],
order: [
[1, 'asc']
]
});
// Add event listener for opening and closing details
$('#termGPA_' + iTermGPACounter + ' tbody').on('click', 'td.details-control', function() {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(formatTermCourseGrades()).show();
tr.addClass('shown');
}
});
iTermGPACounter += 1;
}
});
}
function formatTermGPA(table_id) {
return '<table class="table table-striped" id="termGPA_' + table_id + '">' +
'<thead><tr><th></th><th>Term #</th><th>Term GPA</th></tr></thead></table>';
}
function formatTermCourseGrades() {
return '<table class="table table-striped" id="termCourseGrades">' +
'<thead><tr><th>Course Name</th><th>Letter Grade</th></tr></thead><tr><td>Math</td><td>B+</td></tr></table>';
}
I posted this question in the DataTables forum as well and received an answer...in a nutshell, as a starting point I copied from the DataTables examples a table with a single child table. When I added the second child table, I didn't think to rename the variables, so it kept calling back to the parent table :(. Below is a working fiddle of the final result:
working fiddle
function loadDetailsByCourse() {
$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
url: "WebServices/myStudentProfile.asmx/getDetailsByCourse",
data: JSON.stringify({ pageID: pageID }),
dataType: "json",
cache: false,
success: function (response) {
gpa = response.d;
var yearTable = $('#msGrades').DataTable({
paging: false,
data: gpa,
columns: [
{
className: 'term-details-control openClose',
orderable: false,
data: null,
defaultContent: ''
},
{ data: "schoolYearLabel" },
{ data: "grade" },
{ data: "location" },
{ data: "gpaValue" }
],
order: [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#msGrades tbody').on('click', 'td.term-details-control', function () {
var tr = $(this).closest('tr');
var row = yearTable.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(formatTermGPA(iTermGPACounter)).show();
tr.addClass('shown');
var termTable = $('#termGPA_' + iTermGPACounter).DataTable({
data: row.data().termGPA,
paging: false,
searching: false,
columns: [
{
className: 'course-details-control openClose',
orderable: false,
data: null,
defaultContent: ''
},
{ data: "term" },
{ data: "gpaValue" }
],
order: [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#termGPA_' + iTermGPACounter + ' tbody').on('click', 'td.course-details-control', function () {
var tr = $(this).closest('tr');
var closestTable = tr.closest("table");
var row = closestTable.DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(formatTermCourseGrades(iCourseCounter)).show();
tr.addClass('shown');
var courseTable = $('#courseGrades_' + iCourseCounter).DataTable({
data: row.data().termCourseGrades,
paging: false,
searching: false,
columns: [
{ data: "courseName" },
{ data: "letterGrade" }
],
order: [[1, 'asc']]
});
}
iCourseCounter += 1;
});
iTermGPACounter += 1;
}
});
}
})
}
function formatTermGPA(table_id) {
return '<table class="table table-striped" id="termGPA_' + table_id + '">' +
'<thead><tr><th></th><th>Term #</th><th>Term GPA</th></tr></thead></table>';
}
function formatTermCourseGrades(table_id) {
return '<table class="table table-striped" id="courseGrades_' + table_id + '">' +
'<thead><tr><th>Course Name</th><th>Letter Grade</th></tr></thead></table>';
}

render jquery datatable boolean column with check and x

How do you render a boolean true/false value coming from JSON to a green check or a red x on a jquery datatable?
For example, something like:
&check;
&check;
and
&cross;
&cross;
Using bootstrap glyphicons you can do this:
personTable = $("#person-table").DataTable({
order: [1, "desc"],
"autoWidth": false,
ajax: {
url: uri,
dataSrc: "",
},
"columns": [
{ "data": "FirstName", "title": "Name" },
{ "data": "Address", "title": "Address" },
{ "data": "IsActive", "title": "Active" }
],
"columnDefs": [
{
"render": function (data, type, row) {
return row.FirstName + " " + row.LastName;
},
"targets": 1
},
{
"render": function (data, type, row) {
return (data === true) ? '<span class="glyphicon glyphicon-ok"></span>' : '<span class="glyphicon glyphicon-remove"></span>';
},
"targets": 2
}
]
});
Then add some css like this:
/* Green check. */
.glyphicon-ok {
color: green;
}
/* Red X. */
.glyphicon-remove {
color: red;
}
For my purposes I am ok with adding this custom CSS to a pre-defined bootstrap icon. If you don't want that, define and use your own class.