AJAX
$(document).ready(function(){
//remove product from cart
$(\".delete-product-cart\").click(function(e){
var id = $(
I think this will help you. I used as manny of your own code. There are many points of improvements but i guess this is a learning project of yours
<?php
/**
* remove_from_cart.php
*/
// Test if the script gets loaded by a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
session_start();
$id = (int)$_POST['id'];
// remove the item from the array
unset($_SESSION['cart'][$id]);
}
/**
* cart.php
*/
if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {
// get the product ids
// Wy do this? your session is already an array with the ids
$ids = array();
// And here you add the key of the array to ids and not the product_id so you will get the wrong products
foreach ($_SESSION['cart'] as $id => $value) {
array_push($ids, $id);
}
$stmt = $product->readByIds($_SESSION['cart']); // Instead of $ids you can add the session
// this works, but add your fetch in your readByIds method to keep your code cleaner and return the array with products
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<div class="product-row">
<p><?= $row['product_name'];?></p>
<p><?= $row['product_price'];?></p>
<button type="button" class="delete-product-cart" data-id="<? $row['product_id']; ?>">Remove</button>
</div>
<?php
}
} else {
// Cart session doesnt exist or is empty
// Let the user know the his cart is empty
}
?>
<script>
$(function () {
// Remove product from cart
$(".delete-product-cart").click(function (e) {
var
button = $(this),
product_id = button.data('id');
$.ajax({
url: "remove_from_cart.php",
type: "POST",
data: {
id: product_id,
},
beforeSend: function() {
// Disable the button, to prevent duplicate request
button.attr('disabled', 'disabled');
},
success: function (data) { // Response data is not used now
button.parent().fadeOut(300, function () {
button.remove();
});
},
complete: function() {
// Make the button enabled again, for when the delete function didnt work the button can be pressed again
button.removeAttr('disabled');
}
error: function () {
//Do Something to handle error
}
});
});
});
</script>