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

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);
},
});
}

Related

How to add buttons in a DataTables using loop

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

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).

Load more button works just once

I have a table named tbl_video that consist of two fields (video_id, video_title What I want to add a load more button using Ajax JQuery like social networking sites .I am able to get the first two records but when I try second time nothing happens. I dont get any errors .What am i doing wrong .
this my index.php file I create table structure here and then fetch two records.And get the second record's id value and send it to the more.php file
<body>
<table class="table table-bordered" id="load_data_table">
<thead>
<tr>
<td width="15%">Video Id</td>
<td>Video Title</td>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($result)) {
$video_id = $row['video_id']; ?>
<tr>
<td><?php echo $row['video_id']; ?></td>
<td><?php echo $row['video_title']; ?></td>
</tr>
<?php
}
?>
<tr id="remove_row"><td><button type="button" id="more" class="btn btn-success form-control"
data-id="<?php echo $video_id; ?>">More</button></td></tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#more').click(function(){
var id=$(this).data("id");
$.ajax({
url:"more.php",
data:{id:id},
method:"post",
success:function(data){
if(data!=''){
$('#load_data_table').append(data);
$('#remove_row').remove();
}
else{
$('#more').html("No Data");
}
}
and this the more.php file.I think it is self explanatory
$id = $_POST['id'];
$output = '';
$db = mysqli_connect('localhost', 'root', '', 'testing');
$data = mysqli_query($db, "select * from tbl_video where video_id >{$id} limit 2");
if (mysqli_num_rows($data)) {
while ($row = mysqli_fetch_array($data)) {
$output .= '
<tbody>
<tr>
<td>'.$row['video_id'].'</td>
<td>'.$row['video_title'].'</td>
</tr>
';
}
$output .= '
<tr id="remove_row"><td><button type="button" id="more" class="btn btn-success form-control"
data-id="'.$row['video_id'].'">More</button></td></tr></tbody>
';
echo $output;
}
any help would be appriciated.
When you add a new row and there is a new button for More
It has the same id as the original button so there is a conflict there
also the javascript needs to be initiliazed something like this
PHP:
$output .= '<tr id="remove_row"><td><button type="button" class="more btn btn-success form-control" data-id="'.$row['video_id'].'">More</button></td></tr></tbody>';
Javascript:
<script>
function moreButton() {
$('.more').click(function(){
var id=$(this).data("id");
$.ajax({
url:"more.php",
data:{id:id},
method:"post",
success:function(data){
if(data!=''){
$('#load_data_table').append(data);
$('#remove_row').remove();
moreButton();
}
else{
$('.more:last').html("No Data");
}
}
});
}
$(document).ready(function(){
moreButton();
});
Don't forget to remove the id of the more button to a class with .more

Requested unknown parameter '0' from the data source for row 1 in DataTables

When I try to retrieve data from my database to the table, I get the below error:
DataTables warning (table id = 'myTable'): Requested unknown parameter '0' from the data source for row 1
Below is the js that I used
<script>
$(document).ready(function() {
$('#myTable').dataTable();
});
</script>
Below is my table
<table id="myTable" class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Options</th>
</tr>
</thead>
<tbody id="myTableOK">
<?php echo $tableQuery ?>
</tbody>
</table>
php Code
function tableQuery($linkDB){
$out = '';
$query = $linkDB -> query("SELECT id,name,date
FROM tbl_mytable ORDER BY name ASC");
if($query -> num_rows != 0){
while($listOK = $query -> fetch_assoc())
{
$out .= '
<tr>
<td>'.$listOK ['name'].'</td>
<td>'.$listOK ['date'].'</td>
<td class="centerTXT"><a data-action="edit" class="btn btn-xs" href="'.$listOK ['id'].'">Edit</a> <a data-accion="delete" class="btn btn-xs" href="'.$listOK ['id'].'">delete</a></td>
<tr>
';
}
}
else{
$out = '
<tr id="noData">
<td colspan="5" class="centerTXT">DATABASE WITHOUT DATA</td>
</tr>
';
}
return $out;
}
I'm using DataTables.
Can someone tell me why am I getting that error and how to retrieve the data to the table?
It is because I'm using PHP to dynamically show the data records of the database?
Thank you.
In your script you have echo $tableQuery, but tableQuery is a function. Try this:
<?php echo tableQuery(); ?>
Datatables need the exact number of column in the "thead" and the "tbody", otherwise it will throw an error.
When your $query return no result, you should not return any text at all, Datatables will display "No data available in table" which you can change by passing an argument to the Datatable constructor :
<script>
$(document).ready(function() {
$('#myTable').dataTable(
"oLanguage": {
"sEmptyTable": "My Custom Message On Empty Table"
}
);
});
</script>
Source :
How to show empty data message in Datatables

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