change cell value on button click - php

I have a table with the following.
Table parts_stock
*--------------------*
| id | sku | stock |
| 1 | 101 | 2 |
| 2 | 102 | 3 |
*--------------------*
This is my code so far, i'm sure there are many ways to achieve this but ideally I want the qty value to change based on which button is clicked on without the page being refreshed (AJAX probably).
<tbody>
<?php
$query = 'SELECT stock_id, sku, in_stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['stock_id'];
$sku = $row['sku'];
$qty = $row['in_stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td>".$qty."</td>";
echo "<td>
<a href='' onclick='rem_qty()' id='minus' name='minus' class='btn btn-warning'><span class='glyphicon glyphicon-minus'></span></a>
<a href='' onclick='add_qty()' id='plus' name='plus' class='btn btn-success'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
</td>";
}
}?>
</tbody>
ajax_search.js
<script>
function rem_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: {id_m: stock_id}
});
}
function add_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: 'id_p: stock_id'
});
}
</script>
update_qty.php file
<?php
if (isset($_POST['id_m'])) {
$r = $_POST['id_m'];
echo $r;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$r."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$rem_stock = $row['in_stock'];
$rem_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$rem_stock."' WHERE stock_id = '".$value."'";
$inv_query = mysqli_query($connection, $inv_update);
}
if (isset($_POST['id_p'])) {
$a = $_POST['id_p'];
echo $a;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$a."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$add_stock = $row['in_stock'];
$add_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$add_stock."' WHERE stock_id = '".$value."'";
}
?>

A simple and complete solution: just change mysqli_connect config in both page
index.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); //change dbname
$query = 'SELECT id, sku, stock FROM parts_stock';
//confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
?>
<table>
<tr>
<th>Sku</th>
<th>Stock</th>
<th>Action</th>
</tr>
<?php if($num>0){
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td class='stock-{$id}'>".$qty."</td>";
echo "<td>
<a class='btn btn-warning' onclick='add_qty({$id})' href='#'><span class='glyphicon glyphicon-minus'>Value Add</span></a>
<a class='btn btn-success' onclick='rem_qty({$id})' href='#'><span class='glyphicon glyphicon-plus'>Value Deduct</span></a>
</td>";
echo "</tr>" ;
}
}?>
</table>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
function add_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'add'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
function rem_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'rem'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
</script>
update_qty.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); ////change dbname
header('Content-Type: application/json');
$success = false; $msg ="";
if (isset($_POST['id'])) {
$id = $_POST['id'];
$cur_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$cur_query = mysqli_query($connection, $cur_inv);
if(mysqli_num_rows($cur_query)>0){ //if id is exist in database
if($_POST['type']=="add"){
$inv_update = "UPDATE parts_stock SET stock = (stock+1) WHERE id = {$id}"; //increase your stock dynamically
}elseif($_POST['type']=="rem"){
$inv_update = "UPDATE parts_stock SET stock = (stock-1) WHERE id = {$id}"; //increase your stock dynamically
}
$inv_query = mysqli_query($connection, $inv_update);
if($inv_query){ //If sucess
$msg = "Successfully Updated";
$success = true;
}else{ //if failed
$msg = "Failed to Update";
}
}else{
$msg="Id is not found.";
}
$last_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$last_query = mysqli_query($connection, $last_inv);
$row = mysqli_fetch_assoc($last_query);
echo json_encode(array('success'=>$success, 'msg'=>$msg, 'data'=>$row));
}
?>
No need extra js file just index.php and update_qty.php

Working example
demo.php
<?php
$query = 'SELECT id, sku, stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
$data = "";
$data .= "<tr>";
$data .= "<td>{$sku}</td>";
$data .= "<td>{$qty}</td>";
$data .= "<td>
<a class='btn btn-warning' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-minus'></span></a>
<a class='btn btn-success' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
echo $a;
exit;
}
}?>
AJAX:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<table >
<tr>
<th>Id</th>
<th>Sku</th>
<th>Qty</th>
</tr>
<tbody id="mytable">
</tbody>
</table>
<button id="clickme">Click</button>
<script>
$(document).ready(function(){
$("#clickme").click(function() {
$.ajax({
url:"demo.php",
type:"GET",
beforeSend:function() {
$("#mytable").empty();
},
success:function(response){
$("#mytable").append(response);
}, error:function(err) {
console.log(err);
}
})
});
});

In your HTML Button to have a onClick event like this onclick="buttonSubtract1('<?php if(isset($val['itm_code'])){echo $val['itm_code'];}?>')"(You can fetch the itm_code from your db).Then Write your AJAX for Request and Response. And You need to Pass the itm_code through var x. e.g for like this xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
In AJAX file
$item_cat = $_SESSION['item_cat']; // get a category from session
$iname=$_GET['val']; //get the value from main php file
if(!key_exists($item_cat)
{
$_SESSION['main'][$iname] = "1";
}
else
{
$_SESSION['main'][$item_cat][$iname]++;
}
echo "<pre>";
print_r($_SESSION['main']);
echo "</pre>";
EDIT 1
function buttonSubtract1(x)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.location.assign('items.php');
}
}
xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
xmlhttp.send();
}

Related

PHP Script running without redirection

I have a database with two tables: accounts and recipes(each have their own ID column).
I have a page that displays all the recipes. I want to enable users to add recipes to their favourites in accounts table. Once user is logged in, $_SESSION['user_id'] is set.
I have script that will add the recipe id to the favourites in accounts table, but I don't know how to run it without redirecting from the page that displays all recipes.
Here is what i have so far:
_view.php
<?php
$result = $mysqli->query("SELECT * FROM recipes");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "Error!";
echo "<div class='error-mess'>" . $_SESSION['message'] . "</div>";
}
else {
while ($row = mysqli_fetch_array($result)) {
$slug = $row['slug'];
$ingr = json_decode($row['ingr']);
$ingr_count= count($ingr);
$id = $row['id'];
echo '<div class="container recipe mb-2">';
echo '<img class="" src="/images/recipes/';
echo $row['img'];
echo '"/>';
echo '<div class="title-cats"><a href = "/recipe_preview.php?slug=' . $slug . '">';
echo $row['title'];
echo '</a></div>';
echo '<h4>Ingredients:</h4><br>';
for($i = 0; $i<$ingr_count;$i++){
$num = $i + 1;
echo $num . '. ';
$ingrs = json_decode($ingr[$i],true);
print_r($ingrs[0]);
echo '<br>';
}
echo '<br><button type="submit" class="btn" name="add">Read More</button>';
//favourites link
echo '<span class="fa fa-heart ml-3"></span>';
echo '</div><hr>';
}
}
_favourite.php
<?php
//relationship
require 'db.php';
$user_id = $_SESSION['user_id'];
//$favourite_id = $_POST['fav'];
$favourite_id = $_GET["id"];
echo $favourite_id;
echo $user_id;
$result = $mysqli->query("SELECT favourites FROM accounts WHERE id ='$user_id'");
if ( $result === null) {//doesnt work
$favs = array();
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
echo 'null';
}
else{
$favs = array();
$result = json_decode($result,true);
array_push($favs, $result);
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
}
$sql = "UPDATE accounts SET favourites ='$new_favs' WHERE id = '$user_id'";
if ( $mysqli->query($sql)){
echo '<div class="error-mess">Recipe sucessfully saved!</div>';
}
else{
echo '<div class="error-mess">NOT</div>';
}
.js -jquery library is there
$(document).ready(function() {
$('#favourite').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
id: $(this).data('id'),
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});

PHP POST form after AJAX call

Problem: My php form does not submit.
This is my page:
It has a php rendered list of colors:
<div class="table-container">
<div>
<table class="myTable" id="myTable">
<tr class="header">
<th>Variants</th>
<th>Size</th>
<th>Price (€)</th>
</tr>
<?php
$current_name = $_GET['prod-name'];
$get_product_det = "SELECT * FROM product_details WHERE product_name='$current_name' ORDER BY position";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$id = $row_product_det['id'];
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
$position = $row_product_det['position'];
echo "<tr data-index='$id' data-position='$position'>
<td><a id='$id'>$product_variant</a></td>
<td>$product_size</td>
<td>$product_price</td>
</tr>";
};
?>
</table>
</div>
Each color has a unique ID. Clicking on a color fires the AJAX script that works fine:
<div class='product-det-div' id='product_details'>
<script>
var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
links[i].onclick = function() {
var id = this.id;
var product_details = document.getElementById('product_details');
var request = new XMLHttpRequest();
request.open('POST', 'product_details.php?variant_id=' + id, true);
request.onreadystatechange = function() {
if (request.readyState === 4 & request.status === 200) {
product_details.innerHTML = request.responseText;
} else {
product_details.innerHTML = 'An error occurred during your request: ' + request.status + ' ' + request.statusText;
}
};
request.send();
};
};
</script>
</div>
When the ajax call happens, what happens to the URL of the page? I'm passing the ID of the color through the URL but when trying to GET it with PHP it seems it doesn't find it.
Here's the code of the page:
$current_id = $_REQUEST['variant_id'];
$get_product_det = "SELECT * FROM product_details WHERE id=$current_id";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
echo "
<form action='' method='post'>
<h2 style='margin-bottom: 20px;'>$product_variant</h2>
<div><label>Nome Prodotto</label><input value='$product_variant'></div>
<div><label>Dimensione</label><input value='$product_size' type='number' name='product_size'></div>
<div><label>Prezzo (€)</label><input value='$product_price' id='product_price' name='product_price'></div>
<button type='submit' name='edit_variant_btn'>Send</button>
</form>
";
if(isset($_POST['edit_variant_btn'])) {
$variant = $_POST['product_size'];
$current_id = $_REQUEST['variant_id'];
$update_size = "UPDATE product_details SET size = '$variant' WHERE id = '$current_id'";
$run_update = mysqli_query($con, $update_size);
if($run_update) {
echo "<script>window.open('variable_product.php?prod-name=Polycolor', '_self');</script>";
}
}
};
?>
Thank you for your time, any help appreciated.
EDIT: I tried all the changes you all adviced, also tried $_REQUEST["variant_id"] as Banujan Balendrakumar said, but still no result.
The only way I found to make it work was to change the form action from this:
<form action='' method='post'>
to
<form action='product_details.php?variant_id=$current_id' method='post'>
This way it works because on button click, it opens that page and gets the ID value from there but it's just a way to get around the problem...
Any other ideas?
It's working for me....
<div class="table-container">
<div>
<table class="myTable" id="myTable">
<tr class="header">
<th>Variants</th>
<th>Size</th>
<th>Price (€)</th>
</tr>
<?php
$con = new mysqli('localhost','root','','check');
$get_product_det = "SELECT * FROM product_details ORDER BY position";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$id = $row_product_det['id'];
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
$position = $row_product_det['position'];
echo "<tr data-index='$id' data-position='$position'>
<td><a id='$id'>$product_variant</a></td>
<td>$product_size</td>
<td>$product_price</td>
</tr>";
};
?>
</table>
</div>
<div class='product-det-div' id='product_details'>
<script>
var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
links[i].onclick = function() {
var id = this.id;
var product_details = document.getElementById('product_details');
var request = new XMLHttpRequest();
request.open('POST', 'product_details.php?variant_id=' + id, true);
request.onreadystatechange = function() {
if (request.readyState === 4 & request.status === 200) {
product_details.innerHTML = request.responseText;
} else {
product_details.innerHTML = 'An error occurred during your request: ' + request.status + ' ' + request.statusText;
}
};
request.send();
};
};
</script>
</div>
product details
<?php
$current_id = $_REQUEST['variant_id'];
$con = new mysqli('localhost','root','','check');
$get_product_det = "SELECT * FROM product_details WHERE id=$current_id";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
echo "
<form action='' method='post'>
<h2 style='margin-bottom: 20px;'>$product_variant</h2>
<div><label>Nome Prodotto</label><input value='$product_variant'></div>
<div><label>Dimensione</label><input value='$product_size' type='number' name='product_size'></div>
<div><label>Prezzo (€)</label><input value='$product_price' id='product_price' name='product_price'></div>
<button type='submit' name='edit_variant_btn'>Send</button>
</form>
";
if(isset($_POST['edit_variant_btn'])) {
$variant = $_POST['product_size'];
$current_id = $_REQUEST['variant_id'];
$update_size = "UPDATE product_details SET size = '$variant' WHERE id = '$current_id'";
$run_update = mysqli_query($con, $update_size);
if($run_update) {
echo "<script>window.open('variable_product.php?prod-name=Polycolor', '_self');</script>";
}
}
};
?>

Ajax success function trigger data

i have problem with my code. Lets say i have PHP site in background and this site do something. Lets say in this site i have $status = "1"; and in my ajax code i have:
$.ajax({
url: 'src/single.php',
type: 'POST',
data: {single:1, id:id},
success: function(data){
$('#live_data').val('');
$('#live_data').html(data);
}
});
and i want to know if it si possible to trigger $status from my php page. Something like
success: function(data){
if (data.status == '1') {
$('#live_data').val('');
$('#live_data').html(data);
} if (data.status == '2') {
$('#search_result').val('');
$('#search_result').html(data);
}
Thank you for help if you can :)
EDIT:
So here is my code:
first is for fetch data from db,
and second is for search data from db,
And third is for fetch single data from db.
It work good but problem is that when i click on row it display results 2times first from show and second from search
But in search it is correct.
This $('#live_data') is for show.php data and $('#search_result') is for search data. And when i click on row from show.php it will display result 2times. First from show.php and second from search.php but when i click on row from search.php it display correctly (only one result). I know it is cuz i have
$('#live_data').val('');
$('#live_data').html(data);
but when i want to hide duplicated result from show.php i do $('#search_result').val(''); but then i hide my single data from search.php
This is why i want to controll it with if statement
I attach images below
ajax for single data fetch:
//jeden zaznam
$(document).on('click', '.clickable-row', function(){
var id = $(this).data("id2");
$.ajax({
url: 'src/single.php',
type: 'POST',
data: {single:1, id:id},
success: function(data){
$('#live_data').val('');
$('#live_data').html(data);
$('#search_result').html(data);
}
});
});
First:
<?php
include("db.php");
$output = "";
$sql = "SELECT * FROM otk";
$result = mysqli_query($conn, $sql);
$output .= "<table class='table table-hover'>
<thead>
<tr>
<th>Číslo zákazky</th>
<th>Pozícia</th>
<th>Stav</th>
<th>Dátum</th>
<th>Operátor</th>
</tr>
</thead>";
while ($row = mysqli_fetch_array($result))
{
$output .= "<tr class = 'clickable-row' data-id2 ='".$row['id_otk']."'>
<td>".$row['kod_otk']."</td>
<td>".$row['poz_otk']."</td>
<td>".$row['stav_otk']."</td>
<td>".$row['datum_otk']."</td>
<td>".$row['op_otk']."</td>
</tr>";
}
$output .= "</table>";
echo $output;
?>
Second:
<?php
if (isset($_POST['search']))
{
include("db.php");
$search_text = mysqli_real_escape_string($conn, $_POST['search_text']);
$search = htmlspecialchars($search_text);
$output = "";
$output .= "
<table class='table table-hover'>
<thead>
<tr>
<th>Číslo zákazky</th>
<th>Pozícia</th>
<th>Stav</th>
<th>Dátum</th>
<th>Operátor</th>
</tr>
</thead>";
$sql = "SELECT * FROM otk WHERE kod_otk LIKE '%".$search."%'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= "
<tr class = 'clickable-row' data-id2 ='".$row['id_otk']."'>
<td>".$row['kod_otk']."</td>
<td>".$row['poz_otk']."</td>
<td>".$row['stav_otk']."</td>
<td>".$row['datum_otk']."</td>
<td>".$row['op_otk']."</td>
</tr>";
}
$output .= "</table>
<div class='d-flex justify-content-center'>
<button class='btn btn-primary' onclick='history.go();'>Späť</button>
</div>";
echo $output;
} else {
echo "Žiadny záznam";
}
}
?>
Third:
<?php
if (isset($_POST['single']))
{
include("db.php");
$id = mysqli_real_escape_string($conn, $_POST['id']);
echo "id je: ".$id;
$sql = "SELECT * FROM otk WHERE id_otk = '".$id."'";
$result = mysqli_query($conn, $sql);
$output = "<table class='table table-hovrt'>
<thead>
<tr>
<th>Číslo zákazky</th>
<th>Pozícia</th>
<th>Stav</th>
<th>Poradové číslo</th>
<th>Technológia</th>
<th>Dokument</th>
<th>Zariadenie</th>
<th>Operátor</th>
<th>Dátum</th>
</tr>
</thead>";
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$output .= "
<tr>
<td>".$row['kod_otk']."</td>
<td>".$row['poz_otk']."</td>
<td>".$row['stav_otk']."</td>
<td>".$row['cislo_otk']."</td>
<td>".$row['tech_otk']."</td>
<td>".$row['dok_otk']."</td>
<td>".$row['zar_otk']."</td>
<td>".$row['op_otk']."</td>
<td>".$row['datum_otk']."</td>
</tr>";
}
$output .= "</table>
<div class='d-flex justify-content-center'>
<button class='btn btn-primary' onclick='history.go(-2);'>Späť</button>
</div>";
echo $output;
} else {
echo "Error: " . mysqli_error($sql);
}
}
?>
Image01:
Image02:
You must get the single and id vars with:
<?php
$single = $_POST['single'];
$id = $_POST['id'];
// do your logic and set it's status
echo json_encode(['status' => $status]);
Then you'll be able to retrieve the status param in your success data.
Your best bet would be to use json_encode()
example:
$result = array();
$result = array('status' => '1');
echo json_encode(result);
With the above, you'll be able to access the status key via jquery.

pdo button delete row

when specific user login it will display what he has books.. and inside each book delete button .. i want delete row when i clicked on delete button ... but when i clicked on delete button it reload the page please i need help
this getbooks function
public function getBooks($start = 0, $limit = 2)
{
$sql_start = $start * $limit;
$sql_limit = $limit;
//SELECT loginUser.username, Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username="loay";
$query = "SELECT Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
//,':start' => $start, ':limit' => $limit
]);
$result = $statment->fetchAll();
echo "<table border='1'>
<form method='POST'>
<tr>
<th>Books</th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' name='delete' value='Delete' method='post' >" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</form";
if(isset($_POST['delete'])){
die("SS");
}
}
I made the delete functionality using jquery and ajax.
Above your form code add:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function deleteBook(b) {
$(document).ready(function() {
var book = $(b).parent('td').prev('td').html();
if(confirm("Are you sure you want to delete book - "+book+"?") == false){
return;
}
var ids = $(b).attr('id').substr(6).split('-');
var book_id_to_delete = ids[0];
var user_id = ids[1];
//alert("book_id is " + book_id_to_delete + ", user_id is " + user_id);
$.ajax({
type: "POST",
url: "" + "deletebook.php",
data: {
'book_id': book_id_to_delete,
'user_id': user_id,
submit: 'submit',
},
success: function(res) {
if (res == "deleted") {
$(b).closest('tr').remove();
} else {
alert(res);
}
}
});
});
}
</script>
In getBooks() function, I added id attribute (containing book and user ids) in delete button so our js code will know which books of a user should be deleted.
Replace your getBooks() function with:
<?php
public function getBooks($start = 0, $limit = 2)
{
$sql_start = $start * $limit;
$sql_limit = $limit;
$query = "SELECT Library.nameOfBook, userBook.book_id, userBook.user_id FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
]);
$result = $statment->fetchAll();
echo "<table border='1'>
<tr>
<th>Books</th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' id='delete".$row['book_id']."-".$row['user_id']."' onclick='deleteBook(this)' name='delete' value='Delete'>" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "";
if(isset($_POST['delete'])){
die("SS");
}
}
?>
Create a class function that handles user's book deletion.
In your User class in User.php, add the following function:
public function deleteBook($book_id, $user_id)
{
$stmt = $this->db->prepare("DELETE FROM userBook WHERE book_id = :book_id AND user_id = :user_id");
$stmt->bindValue(":book_id", $book_id);
$stmt->bindValue(":user_id", $user_id);
return $stmt->execute();
}
The below code will be executed by via ajax so that the chosen book will be deleted from database.
Create a file named - deletebook.php
And add this code:
<?php
include_once('User.php');
if(isset($_POST['submit'])){
$object = new User();
if($object->deleteBook($_POST['book_id'], $_POST['user_id'])){
die('deleted');
}
else {
die("fail");
}
}
?>

How to save a page with html5 webstorage?

I have the following page, which works with MySQL, PHP and AJAX
if I click a NAME (id="orderN") it gives me back the result of the consult, which orders the names descending or ascending.
Is there any way that if you refresh(F5) the page, the result is saved as it was before closing, (ASC or DESC)?
I heard about cookies and HTML5 Storage, which is better than cookies.
if you can do it with either of them, let me know please
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
</head>
<body>
<table>
<tr><th>Name</th></tr>
</table>
<?
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "SELECT NAME
FROM STUDENTS";
$query = mysql_query($consult);
echo "<div id='DivConsult'><table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['NAME'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
<script>
$(document).ready(function() {
var contName = 0;
$('#orderN').click(function() {
contName++;
if (contName % 2 !== 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=ASC",
success: function(data) {
$('#DivConsult').html(data);
}});
}
if (contName % 2 == 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=DESC",
success: function(data) {
//alert(data);
$('#DivConsult').html(data);
}});
}
});
});
</script>
</body>
AJAX:
<?php
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "";
if (isset($_POST['tipOrder'])) {
if ($_POST['tipOrder'] == 'ASC') {
$consult = "SELECT NOMBRE
FROM STUDENTS ORDER BY NAME ASC";
}
if ($_POST['tipOrder'] == 'DESC') {
$consult = "SELECT NAME
FROM STUDENTS ORDER BY NAME DESC";
}}`
$query = mysql_query($consult);
echo "<table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['Name'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
You can do it but just saving a container (any div, span or even body) as
localStorage.variableName = document.getElementById("id");
And then you can access by using
if(Storage!=="undefined" && localStorage.variableName!=null)
now you can set value as
container.val = localStorage.variableName

Categories