I have a checkout page for each product where payments are carried out. I have done so that when one complete's a payment the stock value changes. I am doing this via ajax using the fetch-api to accomplish this. However, the code does not seem to work.
Here is my current code. view_product.php:
</div>
<?php
include 'pdo_connect.php';
$product_id = $_GET['product'];
$stmt = $db->prepare("SELECT * FROM products Where id = :id");
$stmt->bindParam(':id', $product_id );
$stmt->execute();
while($row = $stmt->fetch()){
$stock = $row['stock'];
if ($stock > 0){
echo
"<script>
paypal.Buttons({
style: {
shape: 'rect',
color: 'blue',
layout: 'vertical',
label: 'paypal',
locale: 'en_CY'
},
createOrder: async function(data, actions) {
let stock = (await fetch('get_current_stock.php')).json();
let currentStock = stock['current'];
// you may want to check for amoutTryingToOrder instead of 1
if (currentStock < 1) {
alert('Out of stock, sorry :(');
return false;
}
return actions.order.create({
purchase_units: [{
amount: {
value: ". $row['paypal_price'] .",
currency: 'EUR'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//alert('Transaction completed by ' + details.payer.name.given_name + '!');
alert('Your payment has been processed!');
localStorage.clear();
window.location.href = 'http://localhost/YourLocalArtist/thankyou.php';
const formData = new FormData();
formData.append('amountOrdred', 1);
fetch('update_stock.php', {
method: 'POST',
body: formData
});
})
}
}).render('#paypal-button-container');
</script>";
}
else{
echo
"<h1>OUT OF STOCK</h1>
<script>render('#paypal-button-container');
</script>";
}
}
?>
get_current_stock.php:
<?php
header('Content-Type: application/json');
include 'pdo_connect.php';
$connect = mysqli_connect('localhost', 'root','', 'yourlocalartist-db');
$query = 'SELECT * FROM products ORDER by id ASC';
$result = mysqli_query($connect, $query);
while($product = mysqli_fetch_assoc($result)){
$currentStock = $product['stock'];
echo json_encode([
'current' => $currentStock
]);
}
?>
update_stock.php:
<?php
$_POST['amountOrdered'];
?>
What am I doing wrong? Thank you in advance!
As the comment mentions, your update_stock.php file does absolutely nothing--there are no statements in it, just a variable name.
Specifically, you will need PHP statements that run a SQL query with an 'UPDATE' statement if you want to make changes to existing rows in the database
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.