Dynamically get column names in $aColumns arrary in datatables - php

First I'll mention what I am trying to achieve. I am using CodeIgniter framework of PHP. I have 5 tables in my database and I want to display them in Datatables format on a button click on the display page. I am using server side processing php as data source. So at first I made the code for displaying only one table in Datatable format and was successful in it. Now I want to display one table at a time out of 5 on button click event. But $aColumns length should be equal to number of columns defined in HTML table. Now considering marks tabe, it has 4 columns student_id, exam_id, subject_id and marks_achieved. Now another table is branch and has 2 columns only branch_id and branch_name. So I cannot increase or decrease tags in HTML dynamically so I am confused.
Also I am using this source to create datatables.
You can check my getTable() function here.
jQuery:
$(document).ready(function()
{
$('#datatable').dataTable({
"sPaginationType":"full_numbers",
"bJQueryUI":true,
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"sAjaxSource": "datatable/getTable",
"iDisplayStart": 0,
"iDisplayLength": 10,
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, 'asc']],
"aoColumns": [
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true }
]
})
$('input[type=button]').bind('click', function(){
var param = $(this).attr('id');
data = param + '=1';
$.ajax({
type: 'POST',
url: 'datatable',
data: data
}).done(function( data ) {
console.log(data);
$('#display_area').html(data);
});
})
});
HTML:
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/javascript.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.min.js"></script>
</head>
<body id="dt_example">
<form action="" method="post">
<input type="button" id="display_branch" name="display_branch" value="Display Branch Table" >
<input type="button" id="display_marks" name="display_marks" value="Display Marks Table" >
</form>
<div id="container">
<div id="demo">
<table id="datatable" cellpadding="0" cellspacing="0" border="0" width="100%">
<thead>
<tr>
<th>Student ID</th>
<th>Exam ID</th>
<th>Subject ID</th>
<th>Marks Achieved</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class="spacer"></div>
</div>
</body>
</html>
To get the columns dynamically I have made this change as shown below in datatable.php but it is not working. What is wrong here or I should try some other approach ?
if(isset($_POST['display_marks']))
{
$aColumns = array('student_id', 'exam_id', 'subject_id', 'marks_achieved');
$sTable = 'marks';
}
if(isset($_POST['display_branch']))
{
$aColumns = array('branch_id', 'branch_name');
$sTable = 'branch';
}
EDIT:
The solution posted by user1190992 works but the whole approach is changed. And in that I want to sanitize the headers of the columns. "branch_id" is displayed instead I want to display Branch ID. How can I perform this sanitization ?

This is a very simple way for creating HTML from JSON data dynamically. It doesn't use server side processing though.
JavaScript
$(document).ready(function() {
$(".abutton").click(function() {
$('#myDatatable_wrapper').detach(); //Remove existing table
var table = '<table id="myDatatable" class="table"><thead><tr>';
$.ajax({
url: 'dt.php',
data: "table_id="+$(this).attr("id"),
type: "POST",
success: function (data) {
$.each(data.aoColumns, function(key, value) {
table += "<th>"+value+"</th>";
});
table += "</tr></thead><tbody>";
$.each(data.aaData, function(key, row) {
table += "<tr>";
$.each(row, function(key, fieldValue) {
table += "<td>"+fieldValue+"</td>";
});
table += "</tr>";
});
table += '<tbody></table>';
$('.container').html(table);
$('#myDatatable').dataTable();
},
dataType: "json"
});
});
});
PHP
$table_id = filter_input(INPUT_POST, "table_id", FILTER_SANITIZE_STRING);
$dbconn = mysqli_connect("localhost", "username", "password");
if($table_id == "table1") {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_branch');
}
else {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_marks');
}
if(mysqli_num_rows($sql_query) == 0) {
echo "Check your ID";
exit(1);
}
$data = array();
$data['aaData'] = array();
while($row = mysqli_fetch_assoc($sql_query)) {
$data['aaData'][] = $row;
}
$data['aoColumns'] = array();
while($finfo = mysqli_fetch_field($sql_query)) {
$data['aoColumns'][] = $finfo->name;
}
echo json_encode($data);
HTML
<button id="table1" class="abutton">Table 1</button><br /><button id="table2" class="abutton">Table 2</button>
<div class="container"></div>
Hope this helps.

Related

Data is not Loaded on bootstrap-table using php ajax

i am creating a simple crud system while i loading the data data is not loaded. but i got the data from the all_category.php successfully.i checked through console.log
0: {id: 65, catname: "sad", status: 1}
1: {id: 62, catname: "Pepsi", status: 1}
2: {id: 60, catname: "Mobile", status: 1}
what i tried tried so far i attached code below. i tried this for 2 days but couln't solve this . data is not passing to the table . i attached the screen shot image below
Form design of the table
<table id="tblCenters" data-toggle="table" data-show-refresh="true"
data-show-toggle="true" data-show-columns="true" data-search="true"
data-select-item-name="toolbar1" data-pagination="true" data-sort-name="aid"
data-sort-order="desc">
<thead>
<tr>
<th data-field="catname" data-sortable="true">Category</th>
<th data-field="status" data-sortable="true">Status</th>
<th data-field="opt" data-sortable="true">Edit</th>
</tr>
</thead>
<tr>
</tr>
</table>
Jquery
function get_all() {
$.ajax({
type: 'POST',
url: 'all_category.php',
dataType: 'json',
success: function (data) {
console.log(data);
$('#tblCenters').bootstrapTable('removeAll');
for (var i = 0; i < data.length; i++) {
var btnCell = '<button id="u' + data[i][0] + '" type="button" class="btn btn-success btn-xs" onclick="updateAcc(this)">Edit</button>';
addRow(data[i][1], data[i][2], btnCell);
}
}
,
error: function (data) {
console.log(data);
}
});
function addRow(catname,status,cell) {
$('#tblCenters').bootstrapTable('insertRow', {
index: 1,
row: {
catname: catname,
status:status,
opt:cell
}
});
}
all_category.php
<?php
include("db.php");
$stmt = $conn->prepare("select id,catname,status from category order by id DESC ");
$stmt->bind_result($id,$catname,$status);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("id"=>$id, "catname"=>$catname,"status"=>$status);
}
echo json_encode( $output );
}
$stmt->close();

issue with getting access to part of URL with jquery and php

im getting issue to access the URL display in the display_table_content.php, to display data into my table content.
It works find if I use the php alone without the jquery and ajax.
display_table_content.php
<input type="hidden" name="job_operation" id="job_operation1" value=""/>
<div id="post_details_data" class="tb_body_container"> </div>
url:display_table_content.php?jobs_name=www
JQUERY _ AJAX
$(document).ready(function(){
fetch_user_data();
function fetch_user_data() {
var job_operation = "fetch";
$.ajax({
url:"get_table_content.php",
method:"POST",
data:{job_operation:job_operation},
success:function(data) {
$('#post_details_data').html(data);
$('#tb_jobs').DataTable({
dom: 'lBfrtip',
responsive: true,
"processing":true,
buttons:[{
extend: 'csv',
exportOptions: {columns: [0, 1, 2, 3, 4]}
},
{
extend: 'pdf',
exportOptions: {columns: [0, 1, 2, 3, 4]}
},
{
extend: 'excel',
exportOptions: {columns: [ 0, 1, 2, 3, 4]}
},
{
extend: 'print',
exportOptions: {columns: [ 0, 1, 2, 3, 4]}
}],
"order":[],
"columnDefs":[{"targets":[0, 3, 4],"orderable":false}]
});
}
});
}
});
get_table_content.php
if(isset($_POST["job_operation"])) {
require_once("database.php");
$pdo = pdo_con();
if ($_POST["job_operation"] == "fetch") {
$user_name= $_GET['jobs_name']; <-- Error seems to be from here
$fetch_data = "SELECT * FROM jobs j WHERE jobs_name = $user_name";
$result_User = $pdo->prepare($fetch_data);
$result_User->execute();
$output = '<table id="tb_jobs" class="table table-bordered table-hover table-striped table-responsive-lg" >
<thead class="thead-dark">
<tr>
<th width="60%">Job Details</th>
<th width="15%">Company Name</th>
</tr>
</thead>';
$output .= '<tbody>';
while ($row = $result_User->fetch(PDO::FETCH_ASSOC)) {
$name_text1= $row['aaa'];
$name_text2= $row['ddd'];
$output .= '
<tr>
<td>' .$name_text1. '</td>
<td>' .$name_text2. '</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
}
}
i only the table header are being display, I cannnot fetch the table content due to the 'get' part in the get_table_content.php PHP page
If I have understood waht you want :
This line seems having no sense : $user_name= filter_input(INPUT_GET,"www",FILTER_SANITIZE_STRING); <-- Error seems to be from here
Add in display_table_content.php :
<input type="text" id="job_operation1" value=""/>
<input type="text" id="user_name" value=""/>
<script>
var jobrequest = new Object;
jobrequest.job_operation = $('#job_operation1').val();
jobrequest.user_name = $('#user_name').val();
$.ajax({
url:"get_table_content.php",
method:"POST",
data:jobrequest,
In get_table_content.php :
$job_operation = $_POST["job_operation"];
$user_name = $_POST["user_name"];
If I'm not mistaken you create a HTML table in your back end with php, and then you use DataTables to work with this table you have created, first of all DataTables can use an ajax request to get the content from a json array created in your back end, saying that I think you should do it that way since is more easy to manage for future changes, also it will let the table creation to the front end which is the best aproach, saying that I let you an example to get your table in that way:
Your Html:
<input type="hidden" name="userToFind" id="userToFind" value=""/>
<br>
<button id="btnSearch">Search Operations</button>
<br>
<div class="table-responsive" id="tableOperators" >
<h2>Table Operators</h2>
<table class="display dataTable" id="TablejobOperation" >
<thead>
<tr>
<th>Id</th>
<th>Operation</th>
<th>starts</th>
<th>ends</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Operation</th>
<th>starts</th>
<th>ends</th>
</tr>
</tfoot>
</table>
</div>
<br>
</div>
your php:
if ($_POST["action"] == "SLC" && isset($_POST["user_name"])) {
$user_name= $_POST["user_name"];
$query = "SELECT * FROM jobs j WHERE jobs_name = $user_name";
$command= $conn->prepare($query);
$command->execute();
$result= $command->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
the DataTable javascript:
var jobOperation= $('#TablejobOperation').DataTable({
"destroy": true,
"responsive":{
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,
"ajax": {
"url": 'some.php',
"method": 'POST',
data:{action:"SLC", user_name:username }
},
"columns": [
{"data": "id"},
{"data": "job_operation"},
{"data": "type"},
{"data": "starts"},
{"data": "ends"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});
Your table goes inside a click event:
$("#btnSearch").on('click',function(){
var username = $.trim($('#userToFind').val().replace(/\s+/g, ' '));
var TablejobOperation = $('#tablaSeguros').DataTable();
if ($.fn.DataTable.isDataTable("#TablejobOperation")) {
TablejobOperation.destroy();
$('#TablejobOperationtbody').remove();
}
//the datatable script from the top goes here
})
Hope it helps

insert data checked in data table checkbox codeigniter

I am doing a project for my school subject. I am confused on how to do checking data's in checkbox and when I press a submit button, it will loop to insert into my database. I manage to display/alert the data that is being checked in my data-table.
Here is my Contoller where it populates my data table:
public function getalldocs() {
$listdocs = $this->Admin_model->getdoctors();
$data = array();
foreach ($listdocs as $docs) {
$row = array();
$row[] = $docs->user_fname;
$row[] = $docs->user_mname;
$row[] = $docs->user_lname;
$row[] = '<input name="user_id[]" value="'.$docs->user_id.'" type="checkbox">';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
Here is in my view:
<div class="dataTable_wrapper">
<table id="dataTables-docs" class="table table-striped table-bordered table-hover dataTable dtr-inline" role="grid" style="width: 100%;" width="100%" aria-describedby="dataTables-material">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- dataTable_wrapper -->
here is my javascript to echo the selected check box from my data-table:
function show_docs() {
$("#dataTables-docs").dataTable().fnDestroy();
table = $('#dataTables-docs').DataTable({
"ajax": {
"url": "<?php echo site_url('admin_controls/getalldocs')?>",
"type": "POST",
},
responsive: true,
className: 'select-checkbox',
'bInfo': false,
'paging': false
});
}
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
alert(user_id);
});
now, i want to all that is being checked to be inserted in my database like this:
(myid,selectedfromcheckbox);
here is my screenshot from database table:
Use another ajax to insert the data
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
$.ajax({
type:"post",
data: {user_id:user_id},
"url": "<?php echo site_url('admin_controls/saveData')?>",
success:function(data){
$("#info").html(data);
}
});
});
// Below code in you controller
public function saveData()
{
// code to save in controler
}

Updating a specific row of a table in success function

I have a table where I can edit a specific row in it:
<table class="table table-hover" id="patient_name_table">
<tr id="after_tr_2">
<th>Patient</th>
<th>Phone</th>
<th>D.O.B</th>
<th>Address</th>
<th>Edit</th>
</tr>
<tbody>
<?php foreach($name_array as $tabName) { ?>
<tr id="<?php echo $tabName['id']; ?>">
<td id="nameid"><?php echo ''.$tabName['patient_name'].'';?></a>
</td>
<td id="phoneid"><?php echo $tabName['phone']?></td>
<td id="dobid"><?php echo $tabName['dob']?></td>
<td id="addressid"><?php echo $tabName['patient_address']?></td>
<td><button type="button" class="btn btn-info" id="editInfo">Edit</button>
</tr>
<?php } ?>
</tbody>
</table>
Now I use jquery to get the selected row ID and a dialog box appears:
$(document).ready(function()
{
$("#patient_name_table #editInfo").on('click', function()
{
var id = $(this).closest('tr').attr('id');
var row = $(this).closest('tr');
$('#dialog').dialog({
autoOpen: false,
hide: "puff",
show : "slide",
width: 800,
modal: true
});
$( "#dialog" ).dialog( "open" );
$.ajax({
url: 'info.php',
data: {patient_id: id},
type: 'POST',
dataTyoe: 'JSON',
success:function(res2)
{
$("#name_upd").val(res2['patient_name']);
$("#phone_upd").val(res2['phone']);
$("#dob_upd").val(res2['dob']);
$("#address_upd").val(res2['address']);
},
error:function(res2)
{
console.log("Error");
}
});
$("#upd_info").on('click', function()
{
var upd_name = $("#name_upd").val();
var upd_dob = $("#dob_upd").val();
var upd_phone = $("#phone_upd").val();
var upd_address = $("#address_upd").val();
$.ajax({
url: 'upd_patient.php',
data: {upd_id: id, n: upd_name, d: upd_dob, p:upd_phone, a:upd_address},
type: 'POST',
dataType: 'JSON',
success:function(res3)
{
$( "#dialog" ).dialog( "close" );
},
error:function(res3)
{
console.log("Error Updating info");
}
});
});
});
});
And this is the dialog:
Now after successfully updating the information, I need to change the data of this specific row, without refreshing the page.
The file upd_patient.php script:
$sql = "UPDATE patient_info SET patient_name = :n, patient_address = :a, phone = :p, dob = :d WHERE id = :id AND id_logged = :idl";
$stmt = $conn->prepare($sql);
$stmt->bindValue(":n", $name);
$stmt->bindValue(":a", $address);
$stmt->bindValue(":p", $phone);
$stmt->bindValue(":d", $dob);
$stmt->bindValue(":id", $id);
$stmt->bindValue(":idl", $id_logged);
$exec = $stmt->execute();
$res3 = array("patient_name"=>$name, "dob"=>$dob, "phone"=>$phone, "address"=>$address);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
echo json_encode($res3);
So my question, how to append the new updated information that are added into array res3 into the updated row in my table without refreshing the page.

Search option in jQuery datatables

I'm using jQuery data table in my site. I have integrated the "Multi-tab" functionality and "Ajax Content loading" functionality with the datatables. Now I want to integrate the search option in my data table. My coding is:
$(document).ready(function() {
$("#tabs").tabs({ // My datatable Div Id
"show": function(event, ui) {
var oTable = $('div.dataTables_scrollBody>table.display', ui.panel).dataTable();
if ( oTable.length > 0 ) {
oTable.fnAdjustColumnSizing();
}
}
});
$('#example1').dataTable({ //example1->My first table Id
"bProcessing": true,
"sAjaxSource": "test_data.php", // "test_data.php" provides content for my first table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
$('#example2').dataTable({ // example2->My second table Id
"bProcessing": true,
"sAjaxSource": "test_data2.php", // "test_data2.php" provides content for my second table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
I found in the "Examples of Data table" for the solution of searching option. That coding is:
var asInitVals = new Array();
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"oLanguage": {
"sSearch": "Search all columns:"
}
});
$("tfoot input").keyup( function () {
/* Filter on the column (the index) of this element */
oTable.fnFilter( this.value, $("tfoot input").index(this) );
});
/*
* Support functions to provide a little bit of 'user friendlyness' to the textboxes in
* the footer
*/
$("tfoot input").each( function (i) {
asInitVals[i] = this.value;
});
$("tfoot input").focus( function () {
if ( this.className == "search_init" )
{
this.className = "";
this.value = "";
}
});
$("tfoot input").blur( function (i) {
if ( this.value == "" )
{
this.className = "search_init";
this.value = asInitVals[$("tfoot input").index(this)];
}
});
});
Please guide me to integrate the above solution in my code otherwise please give your suggestion to integrate the search option.
This Example Code may helps you...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Working on Datatable</title>
<!-- Your JQuery Library -->
<script type="text/javascript" language="javascript" src="jquery-1.6.1.min.js"></script>
<!-- Your DataTable library -->
<script type="text/javascript" language="javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$('#userlist').dataTable({
"sDom": '<"toolbar">frtip'
});
} );
</script>
</head>
<body>
<div class="box">
<div style="width:100%;">
<table cellpadding="0" cellspacing="0" id="userlist" width="100%" style="border: 1px solid #0000CC; margin-top:10px;margin-bottom:10px;">
<thead>
<tr style=" background-color:#004677; font-size:14px; color:#fff; font-weight:bold;" height="30">
<th>Slno</th>
<th>User ID</th>
<th>Name</th>
<th>Email</th>
<th>City</th>
<th>Contact Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0001</td>
<td>Hearaman</td>
<td>hearaman.dev#gmail.com</td>
<td>Bangalore,India</td>
<td>9740798429</td>
</tr>
<tr>
<td>2</td>
<td>0002</td>
<td>Raman</td>
<td>raman#gmail.com</td>
<td>Hyderabad,India</td>
<td>886798429</td>
</tr>
<tr>
<td>3</td>
<td>0003</td>
<td>Satish Chandra</td>
<td>satishchandra.surampudi#gmail.com</td>
<td>Bangalore,India</td>
<td>948209876</td>
</tr>
<tr>
<td>4</td>
<td>0004</td>
<td>satish</td>
<td>satish#gmail.com</td>
<td>Bangalore,India</td>
<td>987639029</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
To Download DataTable plug-in and to see more examples, Visit http://datatables.net/
Ok as far as i get it. Add filter option searching i.e.
$(document).ready(function() {
$('#example1').dataTable({ //example1->My first table Id
"bProcessing": true,
"searching" : true,
"sAjaxSource": "test_data.php", // "test_data.php" provides content for my first table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
$('#example2').dataTable({ // example2->My second table Id
"bProcessing": true,
"searching": true,
"sAjaxSource": "test_data2.php", // "test_data2.php" provides content for my second table
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});

Categories