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
Related
I'm trying to get table data to my view table using Codeigniter and AJAX jQuery.
Well, I'm using a document ready function to get the data instead of passing the table data when calling the view on the controller.
Ajax function
$( document ).ready(function() {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
alert("sucesso - " + data);
$('#example1').html(data);
},
error: function() {
alert('Algo falhou, nao caregou a tabela. - ' + data);
}
});
});
Controller method
public function crud_getDataAll($table_name)
{
$data = $this->Administracao_model->getAllData($table_name);
echo json_encode($data);
}
Model method
function getAllData($table_name)
{
$this->db->select('*');
$query = $this->db->get($table_name);
return $query->result();
}
View table
<table id="example1" class="table table-sm table-bordered table-striped Responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if($data){ foreach($data as $row) { ?>
<tr>
<td class="align-middle text-center">
<?php echo $row->id;?>
</td>
<td class="align-middle text-center">
<span class="badge <?php echo $row->classes; ?>">
<?php echo $row->none;?>
</span>
</td>
<?php $ad = $row->adicionar; $el = $row->eliminar; $al = $row->alterar; $pe = $row->pesquisar; ?>
<td>
<?php echo $ad .", ". $el . ", ". $al . ", " . $pe; ?>
</td>
</tr>
<?php } } ?>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
Is there something that I'm doing wrong? Thanks in advance.
Php error:
Severity: Notice
Message: Undefined variable: data
EDITED
output of echo json_encode($data);
[
{
"id": "1",
"nome": "Nivel 0",
"classe": "badge-admin-0",
"adicionar": "1",
"remover": "1",
"alterar": "1",
"pesquisar": "1"
},
{
"id": "2",
"nome": "Teste",
"classe": "badge-danger",
"adicionar": "1",
"remover": "0",
"alterar": "0",
"pesquisar": "0"
}
]
Basically you have 2 options here. First of all, if you're not passing $data to your HTML table, then remove PHP codes:
<table id="example1" class="table table-sm table-bordered table-striped table-responsive">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Nome</th>
<th class="text-center">Ações Permissíveis</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Amostra</th>
<th>Ações Permissíveis</th>
<th>Ação</th>
</tr>
</tfoot>
</table>
but if you're passing the data, leave as it is.
Option 1: Output data as HTML
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'html',
success: function(data) {
$('#example1 tbody').html(data);
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});
Then, in your controller, output data as HTML:
public function crud_getDataAll($table_name)
{
$rows = $this->Administracao_model->getAllData($table_name);
foreach($rows as $row) {
echo '<tr>';
echo '<td class="align-middle text-center">' . $row->id . '</td>';
echo '<td class="align-middle text-center"><span class="badge ' . $row->classe . '">' . $row->nome . '</span></td>';
echo '<td>' . $row->adicionar . ', ' . $row->eliminar . ', ' . $row->alterar . ', ' . $row->pesquisar . '</td>';
echo '</tr>';
}
}
Option 2: Output data as JSON
Just update your AJAX callback:
$( document ).ready(function() {
$.ajax({
type : 'POST',
url : "<?= base_url(); ?>CRUD_Controller/crud_getDataAll/nivel",
cache: false,
processData: false,
dataType: 'json',
success: function(rows) {
if (rows) {
rows.forEach(function(row) {
$('#example1 tbody').append(`<tr><td class="align-middle text-center">${row.id}</td><td class="align-middle text-center"><span class="badge ${row.classe}">${row.nome}</td><td>${row.adicionar}, ${row.eliminar}, ${row.alterar}, ${row.pesquisar}</td></tr>`);
});
}
},
error: function(xhr) {
alert('Algo falhou, nao caregou a tabela. - ' + xhr.statusText);
}
});
});
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();
I want to use AJAX to load data from database and display it using DataTable. The database is loaded and can be seen, but the Datatable shows:
Showing 0 to 0 of 0 entries (filtered from NaN total entries)
<table id="employee_data" class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Department</td>
<td>Job Title</td>
<td>Employee Type</td>
<td>Employee Status</td>
</tr>
</thead>
</table>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#employee_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"searching" : true,
"ajax" : {
url: 'employeeData.php',
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8"
},
"columns": [
{ "data": "eId"},
{ "data": "eName"},
{ "data": "eDepartment"},
{ "data": "eJobTitle"},
{ "data": "eEmployeeType"},
{ "data": "eEmployeeStatus"}
]
} );
});
</script>
employeeData.php
$query ="
SELECT *
FROM employee
ORDER BY employeeID DESC";
$result = mysqli_query($link, $query);
$data = array();
while($row=mysqli_fetch_array($result))
{
$data['data'][] = array(
'eId' => $row['employeeId'],
'eName' => $row['employeeLastName'],
'eDepartment' => $row['department'],
'eJobTitle' => $row['jobTitle'],
'eEmployeeType' => $row['employeeType'],
'eEmployeeStatus' => $row['employeeStatus']
);
}
echo json_encode($data);
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
}
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.