I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
$.ajax({
type: "post",
url: "products.php",
data: {id:id},
success: function(){
$(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
}
});
}
}
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>
Related
I have a normal html table filled with database entries.
I got a plugin to select multiple rows in this table.
Now i want to click on a button and delete the database entry so I need to get the id out of the array and but it in my php script.
But I have not really an idea how to do it.
</div>
<table id="myTable" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM artikel;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td> <?php echo $row["id"]?></td> <?php
?> <td> <?php echo $row["artikelnummer"]?></td> <?php
?> <td> <?php echo $row["name"]?></td> <?php
?> <td> <?php echo $row["preis"]?> €</td> </tr><?php
}
}
?>
</tbody>
</table>
</div>
var $rows = [];
$(function() {
console.log( "ready!" );
// start plugin
$('#myTable').TableSelection({
sort : true, // sort or not (true | false)
status : 'multiple', // single or multiple selection (default is 'single')
}, function(obj){ // callback function return selected rows array
$rows = obj.rows;
});
});
<?php
include_once 'dbh.inc.php';
$artid = ???;
$sql = "DELETE FROM artikel WHERE id= $artid;";
mysqli_query($conn, $sql);
header("Location: ../index.php?daten=success");
You can do it with html attributes. I make a example for you with html, css and javascript.
this is your html.
<table id="tableSelected" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>1</td>
<td>1-1</td>
<td>Test</td>
<td>1</td>
</tr>
<tr data-id="2">
<td>2</td>
<td>2-1</td>
<td>Foo</td>
<td>1</td>
</tr>
</tbody>
</table>
as you can see, every "tr" tag has "data-id" attribute.
var $rows = [];
$(function() {
$('#tableSelected').TableSelection({
sort : true,
status : 'multiple',
}, function(obj) {
$.each(obj.rows, function(i, row){
var id = $('#tableSelected').RowValue(row).attr('data-id') // You can get id with this code
});
});
});
Note: https://codepen.io/yusufilkeroguz/pen/vqPgzZ you can see live preview from here :)
My app is reading information from a database and shows the information to the user using jQuery. If a user clicks on an entry, a div will popup and shows more information.
I want to open these div with a URL. Is it possible? I'm thinking about to use the entry id as a parameter?
Like this: div with entry id = 123 will open a link like this
https://url.de/index.php?param=123
// *** Funktion für Details-Overlay ***
function on(id) {
$.ajax({
url: "AJAX.php",
data: 'id=' + id + '&switch_content=details',
success: function(result) {
$("#data-table").html(result);
}
});
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
#overlay {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=12>Click on me</div>
<!-- OVERLAY -->
<div id="overlay">
<div id="ContainerBox" align="center">
<img onclick="off()" id="imgclose" src="images/auswertung-close.png">
<div id="headerSticky"></div>
<h2>Gesamte Übersicht</h2>
<hr>
<!-- Tabelle für Detailseite -->
<table data-role="table" id="data-table" data-filter="true" data-input="#filterTable-input" class="ui-responsive" border="1" style="overflow-x: auto;">
<!-- AJAX/Informations -->
</table>
</div>
</div>
PHP/AJAX:
<?php
// Verbindung zur Datenbank
$pdo = new PDO('mysql:host=***;dbname=***', '***', '***');
$pdo ->exec("set names utf8");
if ($_GET ['switch_content']=='details'){
// SQL Befehl + ID rausnehmen
$sql_befehlDetail = "SELECT * FROM fair_contact_form WHERE id= :id";
// Ergebnisse aus dem SQL Befehl in $ergebnis ziehen
$ergebnisDetail = $pdo->prepare ($sql_befehlDetail);
$ergebnisDetail->execute(array('id'=>$_GET['id']));
$datenDetail = $ergebnisDetail->fetch();
$search = '/../../../../htdocs/..;
$replace = 'https://url.de';
$karte = str_replace($search, $replace, $datenDetail['businessCard']);
echo '<thead>
<tr>
<td class="" colspan="2"></td>
</tr>
</thead>
<tbody>
<tr>
<td data-priority="2"> ID </td>
<td> '. $datenDetail['id'] .' </td>
</tr>
<tr>
<td data-priority="2"> Handelsmesse </td>
<td> '. $datenDetail['fair'] .' </td>
</tr>
<tr>
<td data-priority="3"> Datum </td>
<td> '. $datenDetail['timestamp'] .' </td>
</tr>
<tr>
<td data-priority="4"> dateTimeOfContact: </td>
<td> '. $datenDetail['dateTimeOfContact'] .' </td>
</tr>
<tr>
<td data-priority="5"> Gesprächsdauer </td>
<td> '. $datenDetail['durationOfContact'] .' </td>
</tr>
</tbody>';
}
else if($_GET['switch_content']=='startseite') {
$sql_befehlGesamt = "SELECT * FROM fair_contact_form ORDER BY id DESC";
$ergebnisGesamt = $pdo->query($sql_befehlGesamt);
?><div data-role="header"></div>
<div role="main" class="ui-content">
<table id="table" border="1" data-filter="true" data-input="#filterTable-input" class="ui-responsive" data-role="table"
id="table-column-toggle" data-mode="columntoggle" class="ui-responsive table-stroke">
<thead>
<tr>
<th data-priority="1" id="sortieren_id">ID</th>
<th data-priority="4" id="sortieren_email" class="ui-table-cell-hidden">E-Mail</th>
<th data-priority="4" id="sortieren_gespraechsinhalt" class="ui-table-cell-hidden">Gesprächsinhalt</th> <!-- classe dient dazu, checkbox auf unchecked zu stellen -->
</tr>
</thead>
<tbody><?php
while ($datenGesamt = $ergebnisGesamt->fetchObject()) {
$dateTimeOfContact = new DateTime($datenGesamt->dateTimeOfContact);
?><tr onclick="on(<?=$datenGesamt->id?>)" style="cursor:pointer">
<td onclick="on(<?=$datenGesamt->id ?>)"><p style="color:#E3000F;"><b><?=$datenGesamt->id ?></b></p></td>
<td><?=$datenGesamt->fair ?></td>
<td><?=$dateTimeOfContact->format('d.m.Y') ?></td>
<td><?=$datenGesamt->author ?></td>
<td><?=$datenGesamt->genderOfContact ?></td>
<td><?=$datenGesamt->nameOfContact ?></td>
<td><?=$datenGesamt->surnameOfContact ?></td>
<td class="ui-table-cell-hidden"><?=$datenGesamt->companyName ?></td>
</tr><?php
} ?>
</tbody>
</table>
</div>
The information in the Ajax div should be reachable with a URL+parameter.
Yes, you can trigger the desired id details on start.
Just add next code to your js file:
// Shorthand for $( document ).ready()
$(function() {
// This code will be run when document will be loaded
var args = window.location.search.substring(1); // Get all URL arg
args = args.split('&').map(arg => arg.split('=')); // convert to array with key, value
args.forEach(function(arg) {
var key = arg[0];
var val = arg[1];
if (key === 'param') { // Check if the URL param is our param, and if yes - open popup
on(val);
}
});
});
i created an appointments table and added two links to accept and reject appointments. the links are displayed in every row of the table but when i click it the text accept & reject are only displayed in the first row & I also need to know how to insert the text that appears after the button click into the db i would request someone to pls provide me some help thanks!
<form method="post" action="delete.php" >
<table cellpadding="0" cellspacing="0" border="0" class="table table-condensed" id="example">
<thead>
<tr>
<th>appoinment ID</th>
<th>Date</th>
<th>time</th>
<th>teacher</th>
<th>parent</th>
<th> accept/reject </th>
<th>label</th>
</tr>
</thead>
<tbody>
<?php
$query=mysqli_query($conn, "select * from `app` left join `par` on par.par_id=app.par_id
left join `tea` on tea.tea_id=app.tea_id
ORDER BY app_id DESC");
if($query === false)
{
throw new Exception(mysql_error($conn));
}
while($row=mysqli_fetch_array($query))
{
$ann_id=$row['app_id'];
$date=$row['date'];
$msg=$row['time'];
$username = $row['username'];
$username = $row['p_username'];
?>
<tr>
<td><?php echo $row['app_id'] ?></td>
<td> <?php echo date('j/m/y',strtotime($row['date'])); ?></td>
<td><?php echo $row['time'] ?></td>
<td><?php echo $row['p_username'] ?></td>
<td><?php echo $row['username'] ?></td>
<td> reject
accept
</td>
<td>
<div id="chgtext">PENDING</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
In jQuery it would look like this:
<td>
reject
accept
</td>
<td>
<div class="chgtext">PENDING</div>
</td>
Then, before closing body tag:
<script>
$(document).ready(function(){
$('.reject').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('reject');
});
$('.accept').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('accept');
});
});
</script>
You can make the code shorter, but I wanted to show you how it works step by step.
I am working with MDL Checkbox where i need to delete all values at once. As i did some research and looks like old method is deprecated : Deprecations for MDL Data Table Checkbox and mdl-data-table--selectable can't be used anymore.
HTML Code:
<div class="load_customer">
<table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--7-col-phone">
<thead>
<tr>
<th>
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" id="table-header" for="table-input">
<input type="checkbox" id="table-input" class="mdl-checkbox__input" />
</label>
</th>
<th>Sr. No</th>
<th>Name</th>
<th>Gender</th>
<th>Date of Birth</th>
<th>Anniversary</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
$select = $pdo->query("SELECT * FROM `accounts` ORDER BY `id` DESC");
while($fetch = $select->fetch()){
?>
<tr>
<td>
<label class="mdl-checkbox child_checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" data="<?php echo $fetch['id'];?>" for="row[<?php echo $i;?>]">
<input type="checkbox" id="row[<?php echo $i;?>]" class="mdl-checkbox__input" />
</label>
</td>
<td><?php echo $i;?></td>
<td><?php echo $fetch['name'];?> </td>
<td><?php echo $fetch['gender'];?></td>
<td><?php echo $fetch['dob'];?></td>
<td><?php echo $fetch['anniversary'];?></td>
<td><?php echo $fetch['address'];?></td>
<td><?php echo $fetch['phone'];?></td>
</tr>
<?php
$i++;
}
?>
</tbody>
</table>
</div>
So after adding it manually it works fine until i load table with ajax. Then it all stops working. I am able to check main checkbox #table-header, but function which checks all checkboxes (MaterialCheckbox.check()) does not works anymore. I checked console & there are no errors in console.
Javascript Code
var arr = [];
$(document).on("click","#table-header input",function() {
var all_elements = document.querySelectorAll('.child_checkbox');
for(var i=0, n=all_elements.length; i<n; i++){
var element = all_elements[i];
if($('#table-header input').is(":checked")) {
element.MaterialCheckbox.check();
var ids = element.getAttribute("data");
arr.push(ids);
}
else {
element.MaterialCheckbox.uncheck();
var removeItem = element.getAttribute("data");
arr = $.grep(arr, function(value) {
return value != removeItem;
});
}
}
});
I am using componentHandler.upgradeAllRegistered() and Checkbox is working fine, but it does not loop through all checkboxes.
$.post("load_customer.php",function(data){
$(".load_customer").html(data);
componentHandler.upgradeAllRegistered();
});
Please help me with this.Thanks.
I am using session variable to keep track of items in the cart. I generate a table using loop to display contents of the cart. The code for table is as follow:
<?php
$count=0;
$grandTotal=0;
foreach($_SESSION['cart'] AS $product) {
$table=$product['table'];
$id=$product['id'];
$Name=$product['name'];
$qty=$product['quantity'];
$price=$product['price'];
$total=$qty*$price;
$grandTotal +=$total;
?>
<tr>
<td class="cart_product">
<img src=<?php $i=2; echo "images/".$table."/".$id.".jpg"?> height="150" width="150">
</td>
<td class="cart_description">
<h4><?php echo $Name?></h4>
<p><?php echo "Web ID: ".$id?></p>
</td>
<td class="cart_price">
<p><?php echo $price?></p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" id="increment"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" id="qty" value="<?php echo $qty?>" autocomplete="off" size="2">
<!-- <p class="cart_quantity_input" name="qunatity" id="qty"><?php echo $qty?></p>-->
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" > - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price"><?php echo $total ?></p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href="addToCart.php?table=men&action=del&id=<?php echo $id ?>"><i class="fa fa-times"></i></a>
</td>
</tr>
<?php
}
$tax=0.15*$grandTotal;
?>
I am having problem with + and - buttons within a tags. I want to increment or decrement value in input field named quantity. But since i am generating table in a loop i do not know the id of each field. I want to do something like this:
<script>
$(document).ready(function () {
$("#increment").click(function () {
var oldval=document.getElementById("qty").value;
var newval=parseInt(oldval);
document.getElementById("qty").value=newval++;
});
});
</script>
But this method always increments first quantity field in the table. How do i get ids of other quantity fields in the table?
Dont use ids inside loop.Just use class for that>check the snippet for a smaple demo
$(document).ready(function () {
$(".increment").click(function () {
var oldval = $(this).prev('.qty').val();
var newval = parseInt(oldval)+ 1;
$(this).prev('.qty').val(newval);
});
$(".decrement").click(function () {
var oldval = $(this).next('.qty').val();
var newval = parseInt(oldval) - 1;
$(this).next('.qty').val(newval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <tr>
<td>sl No</td>
<td>name</td>
<td>Dept</td>
<td>dummy</td>
<td>dummy</td>
<td>dummy</td>
</tr>
<tr>
<td>1</td>
<td>name</td>
<td>
</td>
<td>name</td>
<td>name</td>
<td> </td>
</tr>
<tr>
<td>2</td>
<td>name</td>
<td>Dept</td>
<td>name</td>
<td> <button class="decrement"> - </button>
<input type="text" class="qty" value="1"/>
<button class="increment">+ </button>
</td>
<td>name</td>
</tr>
<tr>
<td>3</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
</tr>
</table>
There are 2 solutions to this problem:
When generating table using php, assign unique id to each row's <a> and <input>, such as #increment_id8878 and #input_id8878. Then when #increment or #decrement button is clicked, operate <input> with corresponding id.
Operate <input> element with jQuery's relative selector.
For example:
$('.increment').click(function() {
var inputEle = $(this).siblings('input');
var originVal = inputEle.val();
inputEle.val(parseInt(originVal) + 1);
});
A jsfiddle is made for the 2nd solution.
BTW, duplicate id should be avoided in HTML code.
Don't use same id for multiple elements instead use class like below
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" class="increment">
same is case of decrement button user class
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" class="decrement"> - </a>
You can bind click event to these anchors and change the quantity in input inside same parent div
$(function(){
$('.increment').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)+1;
$input.val(value);
});
$('.decrement').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)-1;
$input.val(value);
});
});