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
Related
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
Hello Every One i have small problem i will upload multiple images single input file and database store with comma i will stored but i have problem is remove the uploaded images selected and remove the image when we click the image above delete icon that only image deleted
My Code for Retrieve the Multiple images
<div class="panel-body">
<div class="table-responsive">
<table id="dataTableExample1" class="table table-striped table-bordered">
<thead>
<tr>
<th>S.No</th>
<th>Gallery Images</th>
<th>Gallery Name</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<?php
extract($_REQUEST);
$sql="SELECT * FROM `smw_gallery`";
$result = $conn->query($sql);
$count=$result->num_rows;
if ($count > 0) {
$i=1;
while ($row = $result->fetch_object()) {
$primages = $row->smw_gallery_images;
$imgp = explode(",", $primages);
$realPath = '../assets/images/gallery/';
?>
<tr>
<td style="width:10%"><?=$i;?></td>
<td style="width:50%">
<?php foreach($imgp as $img)
{
echo '<a class="example-image-link" href="#" data-lightbox="example-set" data-title="Click the right half of the image to move forward."><img class="example-image" src="'.$realPath.'/'.$img.'" alt="" height="80" width="80" style="margin: 10px;"/></a>';
} ?>
</td>
<td style="width:10%">
<?php
$limit = 30;
$td_title1 = $row->smw_gallery_name;
if (strlen($td_title1) > $limit)
$td_title1 = substr($td_title1, 0, strrpos(substr($td_title1, 0, $limit), ' '))."...";
echo $td_title1;
?></td>
<td style="width:20%">
<center>
<i class="fa fa-pencil-square-o btn btn-warning" aria-hidden="true"></i>
</center>
</td>
</tr>
<?php $i++; } } ?>
</tbody>
</table>
</div>
</div>
the above code Output look like this
each image i will place delete button and hole gallery delete button
how to made to single image delete button and remove that image only remain will be as it is display
You can do it with small help of jquery, ajax and mysql.
On click delete icon you have to make one ajax request with image name and id parameters. Update image name in database using below query. On success ajax response you can remove that image block using jquery.
Html code for image. Just a sample line.
DeleteIcon
Jquery Code
$(document).on('click', '.delete-image', function(){
var $this = $(this);
var imagname = $(this).data('name');
$.post("delete_image.php",
name: imagname,
id: 1
},
function(data, status){
$this.closest(tr).remove(); //Write your remove code for single image
});
})
I have write code is look like this :
<img class="btn-delete" id="photo-<?=$photo_index_key;?>" data-id="<?=$photo_index_key;?>" data-name="<?=$photo_name;?>" style="margin: 3px 1px 74px -17px; cursor: pointer;" src="../assets/images/closes.png";>
each one of indexkey value can taken in jquery var $imageId = $(this).attr('id');
<script>
$(document).on('click', '.btn-delete', function(){
var imageId = $(this).attr('data-id');
var imageName = $(this).attr('data-name');
var dataString = {id:imageId, name: imageName}
$.ajax({
type: "POST",
url: "remove.php",
data: dataString,
cache: false,
success: function(html){
$('#photo'+imageId).remove(); // you can write your logic
}
});
});
</script>
remove.php
//get ajax data:
$id = $POST['id'];
$name = $POST['name'];
UPDATE smw_gallery
SET `smw_gallery_images` = REPLACE(`smw_gallery_images`, $name,'')
WHERE `id` = $id;
What if you do it in appearance.
That is, you can define the array by indexes
<div class="panel-body">
<div class="table-responsive">
<table id="dataTableExample1" class="table table-striped table-bordered">
<thead>
<tr>
<th>S.No</th>
<th>Gallery Images</th>
<th>Gallery Name</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<?php
extract($_REQUEST);
$sql = "SELECT * FROM `smw_gallery`";
$result = $conn->query($sql);
$count = $result->num_rows;
if ($count > 0) {
$i = 1;
while ($row = $result->fetch_object()) {
$primages = $row->smw_gallery_images;
$imgp = explode(",", $primages);
$realPath = '../assets/images/gallery/';
?>
<tr>
<td style="width:10%"><?= $i; ?></td>
<td style="width:50%">
<?php foreach ($imgp as $photo_index_key => $img) {
echo '<a class="example-image-link" href="#" data-lightbox="example-set" data-title="Click the right half of the image to move forward.">
<img class="example-image" src="' . $realPath . '/' . $img . '" alt="" height="80" width="80" style="margin: 10px;"/>
</a>';
echo "<a href='".$realPath . "/remove.php?smw_gallery_id=" . $row->id . "&photo_index_key=" . $photo_index_key . "'></a>";
} ?>
</td>
<td style="width:10%">
<?php
$limit = 30;
$td_title1 = $row->smw_gallery_name;
if (strlen($td_title1) > $limit)
$td_title1 = substr($td_title1, 0, strrpos(substr($td_title1, 0, $limit), ' ')) . "...";
echo $td_title1;
?></td>
<td style="width:20%">
<div style="text-align: center;">
<a href="gallery-edit.php?edit=<?= $row->smw_gallery_id; ?>" title="Edit"><i
class="fa fa-pencil-square-o btn btn-warning" aria-hidden="true"></i></a>
</div>
</td>
</tr>
<?php $i++;
}
} ?>
</tbody>
</table>
</div>
I don't know English. This was done via google translate
remove.php
<?php
if (!empty($_GET['smw_gallery_id'] && !empty($_GET['photo_index_key']))) {
$sql = sprintf("SELECT `smw_gallery_images` FROM `smw_gallery` WHERE `id` = %d", $_GET['smw_gallery_id']);
$result = $conn->query($sql);
$result->fetch_assoc();
if (!is_null($result) && is_array($result)) {
while ($row = $result->fetch_assoc()) {
$smw_gallery_images = explode(",", $row['smw_gallery_images']);
$new_smw_gallery_images = array_splice($smw_gallery_images, $_GET['photo_index_key'], 1);
$new_smw_gallery_images = implode(',', $new_smw_gallery_images);
$updateSql = sprintf("UPDATE smw_gallery SET `smw_gallery_images` = %s WHERE `id` = %d", $new_smw_gallery_images, $_GET['smw_gallery_id']);
$conn->query($updateSql);
}
}
}
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);
},
});
}
I want to pass the value from jquery to php using AJAX, the problem is the value in the php is not properly set.
Here is my sample codes:
Button trigger to pass data into jquery.
<button class="btn btn-info add-percentage"
data-landing_id-percentage="'.$row['hidden_id'] .'"
data-toggle="add-percentage"><i class="glyphicon glyphicon-time"></i></button>
Below is the ajax and jquery code.
<script>
$(".add-percentage").click(function(){
var landing_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
data: {
landing_id: landing_id
},
success: function(msg) {
alert('Email Sent'+msg);
$('#add-percentage').modal('show');
readRecords();
}
});
});
<script>
The result below in the php code is the landing_id is not properly set.
readPercentage.php
<?php
$data = '
<table class="table table-bordered table-hover table-striped" id="ModalMyTable">
<thead>
<tr class="success">
<th ><center>No.</center></th>
<th ><center>Percentage ID</center></th>
<th ><center>Landing ID</center></th>
<th><center>Percentage</center></th>
<th><center>Date Added</center></th>
</tr>
</thead>';
if(isset($_POST['landing_id'])){
$landing_id = $_POST['landing_id'];
$query = mysqli_query($conn, "SELECT
percentage.percent_id,
percentage.landing_id,
percentage.percentage,
percentage.date_recorded
FROM
percentage
WHERE percentage.landing_id = '$landing_id'");
$number = 1;
while($row = mysqli_fetch_assoc($query)) {
$data .= '
<tr>
<td><center>' . $number . '</center></td>
<td><center>' . $row['percent_id'] . '</center></td>
<td><center>' . $row['landing_id'] . '</center></td>
<td><center>' . $row['percentage'] . '%</center></td>
<td><center>' . date("M. d, Y", strtotime($row['date_recorded'])) . '</center></td>
</tr>';
$number++;
}
}else{
$data .='<tr><td colspan="6">Landing id is not properly set!</td></tr>';
}
$data .= '</table>
<script>
{
$(document).ready(function(){
$("#ModalMyTable").DataTable();
readRecords();
});
}
</script>
';
echo $data;
?>
I hope some one can help me in my problem. Thanks in advance.
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