How to add buttons in a DataTables using loop - php

Problem: I would like to ask on how do I add a buttons together with the data inside in the while loop,
I tried adding a html variable and put the buttons there so it would loop but DataTables is giving me an error.
This is the error every time i reload page
DataTables warning: table id=tbl_manageStudents - Requested unknown parameter '4' for row 0, column 4.
and I'm pretty sure that it gives that error since it cannot loop the buttons inside the while loop and DataTables needs to have th and td, equally.
manageUsers.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databaseName = "db_researchrepository";
$conn = new mysqli($servername, $username, $password, $databaseName);
$sql = "SELECT * FROM tbl_students ORDER BY ( 0 + student_id ) ASC";
$result = $conn->query($sql);
$output = array('data' => array());
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$studentNumberId = htmlentities($row["student_id"]);
$studentName = htmlentities($row["student_name"]);
$studentEmail = htmlentities($row["student_email"]);
$studentYrBlock = htmlentities($row["student_yrblock"]);
$output['data'][] = array(
$studentNumberId,
$studentName,
$studentEmail,
$studentYrBlock
);
$html = '
<td>
<input type="submit" name="viewStudents" id="viewStudents" value="View" class="btn btn-info"
data-toggle="modal" data-target="#viewExistingStudents<?php echo $row["ID"];?>">
<input type="submit" name="deleteRecord" id="deleteRecord" value="Delete" class="btn btn-danger"
data-toggle="modal" data-target="#deleteSelectedStudent<?php echo $row["ID"];?>">
</td>
';
}
}
echo json_encode($output);
$conn->close();
?>
This is the code that I used to fetch the data and display it in the DataTable.
<script type="text/javascript">
$(document).ready(function(){
function getData(){
$('#tbl_manageStudents').DataTable( {
'processing':true,
'destroy':true,
'order': [],
'ajax': {
url: "helper/helper_tblManageStudent.php",//path to your server file
type: 'POST'
},
lengthChange: true,
lengthMenu: [
[ 10, 25, 50, -1 ],
[ '10 rows', '25 rows', '50 rows', 'Show all' ]
]
});
}
getData();
})
</script>
this is my table
<div class="container-sm table-responsive" id="tblManageStudent">
<table class="table table-striped table-hover table-condense" id="tbl_manageStudents">
<thead>
<tr>
<th scope="col">Student ID</th>
<th scope="col">Student Name</th>
<th scope="col">Student Email</th>
<th scope="col">Student Year and Block</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
This is the visual structure of my DataTable/Table. There should be a buttons there

Related

Table functions doesn't work when using ajax

So I've been using php for a while now but recently, I've decided to use ajax so I can view live data and I don't have to refresh the page to see changes in the database. And I created a page and the fetch function works but when it's in the table, the table functions doesn't work. At the bottom of the table it says it's showing 0 out of 0 entries and the sort by function and the show {limit} function doesn't work either. It's like somehow the table div doesn't read the data inside.
Here's my code:
<div class="body" >
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover js-basic-example dataTable" >
<thead>
<tr>
<th width="155">Action</th>
<th width="90">LRN</th>
<th width="45">Level</th>
<th>Name</th>
<th width="15">Gender</th>
<th width="65">Type</th>
<th width="110" style="font-size: 14px!important;">Date Enrolled</th>
<th width="40">Card</th>
</tr>
</thead>
<tbody id="live-data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready( function() {
function fetch_data() {
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
console.log(data);
$('#live-data').html(data);
}
});
}
fetch_data();
});
</script>
Here's fetch.php
<?php
include('../global/db.php');
$output = '';
$query ="SELECT * FROM students WHERE status = '0' ORDER BY date_enrolled DESC";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
$date_enrolled = $row['date_enrolled'];
$card = $row['card'];
$stud_birth = $row['stud_birth'];
$age = date('Y', strtotime($stud_birth)); $year = date('Y '); $age = (int)$age; $year = (int)$year;
$sage = $year - $age;
$output .= '
<tr>
<td>
<button type="button" class="btn bg-cyan btn-xs waves-effect" data-toggle="modal" data-target="#'.$row['stud_id'].'">
<i class="material-icons">search</i>
<span>Profile</span>
</button> <button type="button" class="btn bg-orange btn-xs waves-effect" data-toggle="modal" data-target="#'.$row['stud_id'].''.$row['stud_id'].'">
<i class="material-icons">search</i>
<span>Approve</span>
</button>
</td>
<td>'.$row['stud_lrn'].'</td>
<td>'.$row['stud_grade'].'</td>
<td>'.$row['stud_lname'].', '.$row['stud_fname'].' '.$row['stud_mname'].'</td>
<td>'.$row['stud_gender'].'</td>
<td>'.$row['stud_type'].'</td>
<td style="font-size: 12px!important;">'.$date_enrolled = date("M-d-Y g:i A", strtotime($date_enrolled)).'</td>
<td>';
if ($card == "") {
$output .= '
<center>N/A</center>';
}
else {
$output .= '
<center><a target="_blank" href="../image-gallery/20.jpg" data-sub-html="Demo Description">
<img class="img-responsive" src="../image-gallery/thumb/thumb-20.jpg" style="width: 70px; height: 35px;"></a></center>';
}
$output .= '
</td>
</tr>';
}
}
else {
$output .= '
<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
echo $output;
?>
I think you are using dataTable jquery library . Problem is its not right way to use datatabe . you need a json format out from backend like as
{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
],
}
Don't forget to warp with {data:[]} object
after then simply use in ajax
$(document).ready(function() {
$('#live-data').DataTable( {
"ajax": 'fetch.php'
} );
} );
For more ...
https://datatables.net/examples/data_sources/ajax.html

Populating form from table row

I have added a button at the end of the row of my datatable intended to update the information in the database for the specific row chosen.
When I click the update button, a form pops us with the relevant fields to update.
Ideally, I would like the form to be autopopulated with the information from the table row which I have chosen to update
Code...
Table:
<div class="viewalljob tab-pane show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<h2>Edit Job Table</h2>
<table id="edit-job-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="job_id">ID</th>
<th class="job_date">Date</th>
<th class="job_company">Company Name</th>
<th class="job_contact">Contact</th>
<th class="job_from">From</th>
<th class="job_to">To</th>
<th class="job_driver nowrap">Driver</th>
<th class="job_income">Income (£)</th>
<th class="job_payment">Payment (£)</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!--Fetch from Database-->
<!--Connect To Database-->
<?php
$host_name = 'xxx';
$database = 'xxx';
$user_name = 'xxx';
$password = 'xxx';
$conn = mysqli_connect($host_name, $user_name, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT *,AS markup
FROM `table`
GROUP BY id";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<tr>
<td class='job_id'>".$result['id']."</td>
<td class='job_date'>".$result['adddate']."</td>
<td class='job_company'>".$result['customer']."</td>
<td class='job_contact'>".$result['addcontact']."</td>
<td class='nowrap job_from'>".$result['addfrom']."</td>
<td class='nowrap job_to'>".$result['addto']."</td>
<td class='nowrap job_driver'>".$result['adddriver']."</td>
<td class='currency job_income'>".$result['addincome']."</td>
<td class='currency job_payment'>".$result['addpayment']."</td>
<td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td>
<td><button type='button' name='delete' id=".$result['id']." class='btn btn-danger btn-xs delete deletebtn'>Delete</button></td>
</tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<div id="contactForm3">
<h1>Edit Job</h1>
<form id="dataForm" name="dataform" method="POST" action="/">
/**** FORM DATA ****/
</form>
</div>
JS to open form:
$(function() {
// contact form animations
$('.update').click(function() {
$('#contactForm3').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm3");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
I have added the update button using <td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td> I have given the id=".$result['id']." hoping that I can use this to populate the form from the ID
I am assuming that I will need to connect to the database table, something like:
<form>
<?php
//Connect to Database ... //
$sql = SELECT * FROM `table`
WHERE ID = ???
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<span>
<label> label1 </label>
<input value = ".$result['column'].">
</span>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Im hoping that this is correct and someone can help me do this?
Actually you can acheive this using javascript/jquery, get row element from table displayed, from which you can get every columns/inputs value like as below:
$('.updatebtn').on('click', function(e) {
e.preventDefault();
var row = $(this).closest('tr'); //get table row from displayed table.
var form = $('#contactForm3').fimd('form'); //form to be populate.
//make sure your form input field with same name as the column name.
//now create form_data object with key as same name as column/input name .
var form_data = { 'id' : row.find('.job_id').value(),
'adddate' : row.find('.job_date').value(),
.....
'addpayment' : row.find('.job_payment').value()
}
//Apply loop to populate values in form.
$.each(form_data, function(key, value){
form.find('input[name="'+ key +'"]').val(value);
});
});
Then on form submit update database record/row using PHP (hope you know that well, if not let me know I will update my code).

How can i apply the datatable filters to my php code?

I am getting some data and displaying on the table which i have created in my php code however i want to apply the data table filters but i cannot seem to find a solution. I know in html i can assign an id to the table and then call it from a js script using the following code var table = $('#myTable').DataTable({"dom":"ftip"}); however this doesn't seem to work in my code. Perhaps because i am wrapping the html code in php?
Thanks
<script>
$(document).ready(function(){
var table = $('#myTable').DataTable({"dom":"ftip"});
});
</script>
<?php
$conn = mysqli_connect('localhost', 'root', '""', 'calendar');
extract($_POST);
if(isset($_POST['readrecords'])){
$data = '<table class="table table-bordered table-striped" id="myTable">
<tr class="bg-dark text-white">
<th>No.</th>
<th>Title</th>
<th>Driver</th>
<th>Date</th>
</tr>';
$displayquery = "SELECT id,title, driver, start FROM `events` ";
$result = mysqli_query($conn,$displayquery);
if(mysqli_num_rows($result) > 0){
$number = 1;
while ($row = mysqli_fetch_array($result)) {
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['title'].'</td>
<td>'.$row['driver'].'</td>
<td>'.$row['start'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-success">Edit</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
$data .= '</table>';
echo $data;
}
?>
function readRecords(){
var readrecords = "readrecords";
$.ajax({
url:"backend.php",
type:"POST",
data:{readrecords:readrecords},
success:function(data,status){
$('#records_content').html(data);
},
});
}

TableEdit Plugin - Two tables on same page - TableEdit Plugin works ONLY when both Tables have Data

I have a single php webpage where i have two result tables. I have applied TablEdit Plugins to add live Edit / Delete features.
It works perfectly ONLY when both the Tables have results, if any of them is empty, the TablEdit Plugin (Save/Delete do not appear) doesnt work.
I have separated the $(document).ready(function(){ } for each table and placing them in two different blocks. BUT same problem.
<!-- UNPAID TABLE -->
$id = $_GET ['id'];
$query = "SELECT * FROM dues INNER JOIN institutions ON institutions.id =
dues.idfk and dues.idfk ='$id' and dues.dstatus ='Unpaid'";
$data = mysqli_query($con,$query);
$total = mysqli_num_rows ($data);
if($total != 0)
{
?>
<table id="unpaid_table" class="table table-bordered">
<thead>
<tr style='text-align: center;'>
<th style='display: none;'>DID</th>
<th>Year</th>
<th>Amount</th>
<th>Penalty</th>
<th>Total Dues</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
while ($result = mysqli_fetch_assoc($data))
{
echo "
<tr style='text-align: center;'>
<td style='display: none;'>".$result ['did']."</td>
<td>".$result ['year']."</td>
<td>".$result['amount']."</td>
<td>".$result['penalty']."</td>
<td>".$result['total']."</td>
<td>".$result['dstatus']."</td>
</tr>";
}
}
else
{
echo "<div style='color:red;'>No Records</div>";
}
?>
</tbody>
</table>
<!-- PAID TABLE -->
$id = $_GET ['id'];
$query = "SELECT * FROM dues INNER JOIN institutions ON institutions.id =
dues.idfk and dues.idfk ='$id' and dues.dstatus ='Paid'";
$data = mysqli_query($con,$query);
$total = mysqli_num_rows ($data);
if($total != 0)
{
?>
<table id="paid_table" class="table table-bordered">
<thead>
<tr style='text-align: center;'>
<th style='display: none;'>DID</th>
<th>Year</th>
<th>Amount</th>
<th>Penalty</th>
<th>Total Dues</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
while ($result = mysqli_fetch_assoc($data))
{
echo "
<tr style='text-align: center;'>
<td style='display: none;'>".$result ['did']."</td>
<td>".$result ['year']."</td>
<td>".$result['amount']."</td>
<td>".$result['penalty']."</td>
<td>".$result['total']."</td>
<td>".$result['dstatus']."</td>
</tr>";
}
}
else
{
echo "<div style='color:red;'>No Records</div>";
}
?>
</tbody>
</table>
<!-- TablEdit Script -->
<script>
$(document).ready(function(){
$('#paid_table').Tabledit({
url:'duesaction.php',
columns:{
identifier:[0, "did"],
editable:[
[1, 'year'],
[2, 'amount'],
[3, 'penalty'],
[4, 'total'],
[5, 'status', '{"Paid": "Paid", "Unpaid": "Unpaid"}']
]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#'+data.did).remove();
}
}
});
});
$(document).ready(function(){
$('#unpaid_table').Tabledit({
url:'duesaction.php',
columns:{
identifier:[0, "did"],
editable:[
[1, 'year'],
[2, 'amount'],
[3, 'penalty'],
[4, 'total'],
[5, 'status', '{"Paid": "Paid", "Unpaid": "Unpaid"}']
]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#'+data.did).remove();
}
}
});
});
</script>
Works perfectly fine when both the Tables has data, but doesnt work if any of tables has no data.
I want it working in both the scenarios.
Please HELP.

Adding a loader to load a table with data jQuery or ajax

Here is the description of my issue:
I have a db connection here:
$host = 'some host credentials';
$dbh = 'My database';
Here is my statement:
$qry = "SELECT some_data FROM some_table LIMIT 1000";
$result = some code here;
Here is my while loop:
echo '<table class="table table-striped table-hover table-bordered" id="example">
<thead>
<tr class="test">
<th style="border: 1px solid #333;">PRODUCTPRICE</th>
<th>PRODUCTNAME</th>
<th>PRODUCTCODE</th>
<th>PRODUCTSALE</th>
<th>PRODUCTPRICE</th>
</tr>
</thead>
<tbody>';
while ($row = mysql_fetch_assoc($result)){
$PRODUCTID = intval($row["PRODUCTID"]);
$PRODUCTNAME = $row["PRODUCTNAME_1"];
$PRODUCTCODE = $row["PRODUCTCODE"];
$PRODUCTSALE = $row["PRODUCTSALE_"];
$PRODUCTPRICE = $row["PRODUCTPRICE"];
echo '<tr class="odd gradeX">
<td>'.$PRODUCTID.'</td>
<td>'.$PRODUCTNAME.'</td>
<td>'.$PRODUCTCODE.'</td>
<td class="center">'.$PRODUCTSALE.'</td>
<td class="center">'.$PRODUCTPRICE.'</td>
</tr>';
}
echo '</tbody>
</table></div>
</div>
</body>
</html>';
I want to make a loader before this content table display because there are more than 50,000 products. Something kind of processing or a circle showing that a content is loading, just a simple one, maybe jQuery or ajax. I have tried many tutorials till now but no success.
here is a scheme for that :
<div id="content"></div>
$.ajax({
url : 'the-above-script.php',
beforeSend : function() {
$("#content").html('<img src="ajax-icon-from-www.ajaxload.info">');
},
success : function(html) {
$("#content").html(html);
}
});

Categories