datatables "No data available in table" - php

This isn't my first time using datatables, but I have an implementation that I can't seem to get to work.
PHP:
public function renderTable() {
$config = $this->container->get('RestorePoint\Configuration');
$displayAndRestoreFrom = $config->get('Settings.displayAndRestoreFrom');
if ($displayAndRestoreFrom !== 'local') {
$remoteStorage = $this->container->get('RestorePoint\RemoteFilesystemFactory');
$service = $remoteStorage->service($displayAndRestoreFrom);
$files = $service->listFilesByCreated($service->getFolder());
} else {
$files = $this->getFilesByCreated($config->get('dir.files'));
}
foreach ($files as &$file) {
if ($displayAndRestoreFrom == 'local') {
$file['id'] = $file['name'];
}
$file['adapter'] = $displayAndRestoreFrom;
$file['created'] = date('Y-m-d H:i:s', $file['created']);
$file['actions'] = '';//view('RestorePoint.actions')->with($file)->render();
}
//echo json_encode(array('data'=>$files), JSON_UNESCAPED_SLASHES);
return response()->json($files);
}
HTML:
<div class="table-responsive">
<table class="table card-table table-vcenter text-nowrap datatable" id="backups" role="grid">
<thead>
<tr>
<td class="w01">Name</td>
<td>Created</td>
<td>Adapter</td>
<td>Actions</td>
</tr>
</thead>
</table>
</div>
JS: (defined in head)
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="./assets/plugins/datatables/datatables.min.js"></script>
<script>
$(document).ready(function () {
$('#backups').DataTable({
//"deferRender": true,
ajax: {
url: "<?php echo url('restorepoint/renderTable'); ?>",
dataSrc: ''
},
columns: [
{data: 'name'},
{data: 'created'},
{data: 'adapter'},
{data: 'actions'}
]
});
});
</script>
JSON:
{"5":{"name":"restorepoint_2019_08_02_05_47_49.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_05_47_49.zip","created":"2019-08-02 05:55:11","adapter":"dropbox","actions":""},"4":{"name":"restorepoint_2019_08_02_07_30_05.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_07_30_05.zip","created":"2019-08-02 03:36:59","adapter":"dropbox","actions":""},"3":{"name":"restorepoint_2019_08_02_07_32_57.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_07_32_57.zip","created":"2019-08-02 03:35:54","adapter":"dropbox","actions":""},"2":{"name":"restorepoint_2019_08_02_07_38_55.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_07_38_55.zip","created":"2019-08-02 03:34:46","adapter":"dropbox","actions":""},"1":{"name":"restorepoint_2019_08_02_08_13_49.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_08_02_08_13_49.zip","created":"2019-08-02 03:33:40","adapter":"dropbox","actions":""},"0":{"name":"restorepoint_2019_07_31_08_10_34.zip","id":"\/restore_point_backups_fagardesignscom\/restorepoint_2019_07_31_08_10_34.zip","created":"2019-07-31 03:54:27","adapter":"dropbox","actions":""}}
Datatables is showing "No data available in table" however, I don't understand why given I've followed this example: https://datatables.net/examples/ajax/custom_data_flat.html

it was the indexes messing things up.
needed to use array_values()
return response()->json(array_values($files));

Related

Dynamic Drag and Drop table rows

I try to make some reorder with drag and drop with PHP and some ajax with this tutorial.
I set up my files for my needs but nothing going on.
On my index.php just change this thing that equal to my MySQL
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
Here is Java script in index.php:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
var selectedData = new Array();
$('.row_position>tr').each(function() {
selectedData.push($(this).attr("id"));
});
updateOrder(selectedData);
}
});
function updateOrder(data) {
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:data},
success:function(){
alert('your change successfully saved');
}
})
}
</script>
</html>
Here is and ajaxPro.php that i change:
require('db_config.php');
$position = $_POST['position'];
$i=1;
foreach($position as $k=>$v){
$sql = "Update `channels` SET `channel_number`=".$i." WHERE `id`=".$v;
$mysqli->query($sql);
$i++;
}
And here is MySQL
When I try to reorder, just want to change field channel_number but nothing goings-on. Where is my mistake
I've change some code, and turn on some log, but still have problem. If anyone can assist will be so happy. Here it is:
index.php
<div class="container">
<h3 class="text-center">Dynamic Drag and Drop table rows in PHP Mysql - ItSolutionStuff.com</h3>
<table id="myTable" class="table table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">#</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody class="row_position">
<?php
require('db_config.php');
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>"> <!-- data-channel-number="<?php echo $user['channel_number'] ?>">-->
<td><?php echo $user['id'] ?></td>
<td class="index"><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- container / end -->
</body>
<!--<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
//console.log(chArray);
}
});
</script>-->
<script>
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function(e, ui) {
$('td.index', ui.item.parent()).each(function (i) {
$(this).text(i+1);
});
};
$("#myTable tbody").sortable({
distance: 5,
//delay: 100,
opacity: 0.6,
cursor: 'move',
helper: fixHelperModified,
update: function() {
var chArray = [];
$('.row_position>tr').each(function() {
chArray.push({
chid : $(this).attr("id"),
chnumber : $(this).closest('tr').find('td.index').text()
});
});
console.log(chArray);
// console.log(data);
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:chArray},
success:function(data){
console.log(data);
//alert('your change successfully saved');
},
error: function (error) {
// console.log(error);
}
})
},
stop: updateIndex
}).disableSelection();
</script>
</html>
ajaxPro.php
error_reporting(1);
require('db_config.php');
$data = $_POST['position'];
echo $data;
//$i=1;
foreach($data as $d){
echo $d['chnumber'];
$sql = "Update channels SET channel_number=".$d['chnumber']." WHERE id=".$d['chid'];
$mysqli->query($sql);
}
It's look good in browser everything is changed (if i move chanel from possition 4 to position 2 it's change on the screen to position 2, but in array chnumber is still 4, and i don't know how to change this.
Here is some pics.
1st order when you load page
Reorder when move channel from pos:4 to pos:2
And here is console log

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

Check all checkboxes on the current page only in datatables

I need a solution for this. Here is what I am trying to do. I have a datatable that has some values and check boxes in the first columns. What I need is when I select the check box in the header it should select all the values in the current page only. But all the check boxes of all the pages get selected.
I also want that, When I navigate to another page of the datatable, the check box selections of all the previous page should be unchecked including the check box in the header.
Hear is my code:
<?php if($acl->can('view_article')){ ?>
<table id="articles" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
<tbody>
<?php
foreach($articles as $article) {
$id = $article["id"];
$uid = $article["uid"];
$article_name = $article["article_name"];
$article_file_path = $article["article_file_path"];
$article_category = $article["article_category"];
$article_demographic = $article["article_demographic"];
$article_word_count = $article["article_word_count"];
$intended_month = $article["intended_month"];
$article_created = $article["article_created"];
if(!empty($article_demographic)) {
$article_demographic = implode(", ",$article_demographic);
}
$article_keywords = $article["article_keywords"];
$article_description = $article["article_description"];
$checkbox = in_array($id, $assigned_articles)? " ":"<input type='checkbox' value=".$id." />";
echo "
<tr class='' data-id='$id'>
" ;
if($acl->can('delete_article'))
echo "<td>$checkbox</td>";
if($acl->can('edit_article')){
echo "<td>" . anchor("articles/edit/$id",$article_name.'- '.$article_word_count,"class='notBtn' title=\"$article_description\"") . " </td>";
}else{
echo "<td>$article_name - $article_word_count</td>";
}
echo "
<td>".short_string($article_category)."</td>
<td>".short_string($article_demographic)."</td>
<td> $intended_month </td>
<td align='right'>$article_word_count</td>
</tr>";
}
?>
</tbody>
</table>
<?php } ?>
<script type="application/javascript">
$(document).on( 'init', function ( e, settings ) {
alert( 'Saved page length is: '+ table.state().length );
} );
$(document).ready(function(){
var oTable = $("#articles").DataTable({
"stateSave": true,
"order": [],
"dom": '<"row" <"col-md-12 space" <"datatable-action pull-left"> <"datatable-n pull-right" l > > >rt <"row" <"col-md-6" i > <"col-md-6" p > >',
"columns" : [
<?php if($acl->can('delete_article')){ ?>
{orderable: false, searchable: false},
<?php } ?>
{"width": "25%" },
null,
null,
{"width": "12%" },
{"width": "10%" },
],
"fnDrawCallback": function( oSettings ) {
$('.popupArticle').viewArticle({
url : '<?=site_url("articles/showArticleInPopup");?>',
title : 'Article Preview',
size : 'lg'
});
}
});
$('#search-inp').on('keyup',function(){
oTable.search($(this).val()).draw() ;
})
if(oTable.state().length != 0)
$('#search-inp').val(oTable.state().search.search);
checkAllCheckbox(oTable);
var deletebtn = '';
<?php if($acl->can('delete_article')){ ?>
var deletebtn = '<i class="fa fa-trash-o"></i>';
<?php } ?>
var assignbtn = '';
<?php if($acl->can('assign_article')){ ?>
var assignbtn = '<i class="fa fa-paperclip"></i>';
<?php } ?>
$("div.datatable-action").html(deletebtn + ' ' +assignbtn);
$('#assignbtn').on('click', function (e) {
e.preventDefault();
eModal.setEModalOptions({loadingHtml : ''});
eModal.iframe('<?= site_url("assignArticles/e/"); ?>', 'Assign Article').then(function (input) {
$('.modal-dialog', window.document).css('width', '80%');
if ($('.modal-footer', window.document).length == 0) {
$('.modal-content', window.document).append('<div class="modal-footer"> </div>');
}
});
});
});
</script>
Here is the code for checkAllCheckbox(oTable);
function checkAllCheckbox(oTable) {
/* Check all in Datatable*/
if ($("#select_all_existent").length != 0) {
var cells = oTable.cells().nodes();
$("#select_all_existent").change(function () {
$(cells).find(":checkbox").prop("checked", $(this).is(":checked"));
});
$(cells).find(":checkbox").change(function(){
if(!$(this).is(":checked")){
$("#select_all_existent").prop("checked", $(this).is(":checked"));
}
else{
if ($(cells).find(":checkbox").length == $(cells).find(":checked").length) {
$("#select_all_existent").prop("checked",true);
}
}
if ($(cells).find(":checked").length > 0) {
$(oTable.table().container()).siblings().find('.help- block').html('');
}
else{
$(oTable.table().container()).siblings().find('.help- block').html('Please select at least one checkbox');
}
});
}
}
Any help on the scenarios that I have mentioned would be appreciated.
In your code made the following changes and try:
change 1: disable sorting of checkbox column
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th data-orderable="false"><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
change 2:
add the following code to script:
$('#articles').on('page.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#articles').on('length.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#select_all_existent').on('change',function () {
checkAllCheckbox(oTable);
});

How to hide form_dropdown in codeigniter

I want to hide form drop down after second selection, because that second combo box it already selected in earlier. Currently i make it to be like this.
$data['year'] = NULL;
but what i need is that variable is disappear after is selected the dropdown 1.
Below is my code.
Controller
function carbyyear() {
$arrCaryear = $this->modelRegister->loadcaryear();
$arrcaryear[''] = 'Please Select';
foreach ($arrCaryear as $caryears) {
$arrcaryear[$caryears->year] = $caryears->year;
}
$data['year'] = $arrcaryear;
$this->load->view('abc',$data);
}
function ajax_car_make() {
if (isset($_POST) && isset($_POST['year'])) {
$year = $_POST['year'];
$arrMakes = $this->modelRegister->loadcarmake($year);
//print_r($arrModels);
$arrmakes[''] = 'Please Select';
foreach ($arrMakes as $makes) {
$arrmakes[$makes->make] = $makes->make;
}
print form_dropdown('make',$arrmakes);
$data['year'] = NULL;
$this->load->view('abc',$data);
} else {
redirect('site');
}
}
function ajax_car_model() {
if (isset($_POST) && isset($_POST['make'])) {
$make = $_POST['make'];
$arrModels = $this->modelRegister->loadmodelfrombrand($make);
//print_r($arrModels);
$arrmodels[''] = 'Please Select';
foreach ($arrModels as $models) {
$arrmodels[$models->model] = $models->model;
}
print form_dropdown('model',$arrmodels);
} else {
redirect('site');
}
}
View
<body>
<div id="container">
<div id="body">
<article>
<table style="margin:0 auto;width:50%" >
<tr>
<td align="center" height="50">
<div id="yearcombox">
<?php
$js = 'id="year" onChange="showMake(this);;"';
echo form_dropdown('year',$year);
?>
</div>
</td>
</tr>
<tr>
<td align="center" height="50"><div id="makecombox"></div> </td>
</tr>
<tr>
<td align="center" height="50"><div id="modelcombox"></div> </td>
</tr>
</table>
</article>
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
$('#yearcombox select').change(function () {
var selYear = $(this).val();
console.log(selYear);
$.ajax({
url: "ajax_car_make",
async: false,
type: "POST",
data: "year="+selYear,
dataType: "html",
beforeSend: function(data) {
$('#makecombox').html('<img src="<?php echo base_url(); ?>/template/images/loader.gif" alt="" width="24" height="24">');
},
success: function(data) {
$('#makecombox').html(data);
},
})
});
});
$(document).ready(function () {
$('#makecombox select').change(function () {
var selMake = $(this).val();
console.log(selMake);
$.ajax({
url: "ajax_car_model",
async: false,
type: "POST",
data: "make="+selMake,
dataType: "html",
beforeSend: function(data) {
$('#modelcombox').html('<img src="<?php echo base_url(); ?>/template/images/loader.gif" alt="" width="24" height="24">');
},
success: function(data) {
$('#modelcombox').html(data);
},
})
});
});
</script>
</body>
No need to load view in ajax response
function ajax_car_make()
{
if (isset($_POST) && isset($_POST['year'])) {
$year = $_POST['year'];
$arrMakes = $this->modelRegister->loadcarmake($year);
//print_r($arrModels);
$arrmakes[''] = 'Please Select';
foreach ($arrMakes as $makes) {
$arrmakes[$makes->make] = $makes->make;
}
echo form_dropdown('make',$arrmakes);
} else {
echo false;
}
}
Change $('#makecombox select').change(function () {
to
$('body').on('change','#makecombox select',function () {

Dynamically get column names in $aColumns arrary in datatables

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.

Categories