I have a website that I’m close to finishing. On the website I have a a simple add-to-cart button that adds items to a shopping cart and then the basket page has a clear, delete and update buttons. There is also a pay with PayPal button. I had this code working first on .php pages.
- shop.php
- basket.php
When I added the item to the cart, I can see it in the shopping cart on the shop.php page and when I went to basket.php, I also see it.
But when I tried to so it in chunks and snippets on Modx, I’m able to add the items to the cart and basket, but I don’t see them in the shopping cart instantly. I need to refresh the page first to see the changes. I’ve tried AJAX but my JavaScript is very limited. Actually my PHP is too…I’m learning
This is my shop.php page. You’ll see php code at the top and also around the shopping cart displaying the items added. You’ll see the html button also.
<?php
// Error checker
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Start or resume the session
session_start();
// Check if the cart array is not initialized in the session, initialize it
if (!isset($_SESSION["cart"])) {
$_SESSION["cart"] = [];
}
// Check if the request is to add an item to the cart
if (isset($_POST["add_to_cart"])) {
// Validate and sanitize input
$product_id = filter_input(INPUT_POST, "product_id", FILTER_SANITIZE_NUMBER_INT);
$quantity = filter_input(INPUT_POST, "quantity", FILTER_VALIDATE_INT, array("options" => array("min_range" => 1)));
if ($product_id !== false && $quantity !== false) {
// Check if the product is already in the cart
if (isset($_SESSION["cart"][$product_id])) {
// If it is, increment the quantity by the selected multiplier
$_SESSION["cart"][$product_id]["quantity"] += $quantity;
}
else {
// If it's not, add it to the cart with the selected quantity
$_SESSION["cart"][$product_id] = array(
"quantity" => $quantity,
"product_name" => "Product " . $product_id,
"product_price" => 250.00,
);
}
}
else {
// Handle invalid input (e.g., display an error message)
echo "Invalid input. Please check your input values.";
}
}
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<!-- head code here -->
</head>
<body class="stretched">
<header id="header" class="header-size-sm" data-sticky-shrink="false">
<!-- some header code here -->
<!-- Top Cart
============================================= -->
<?php foreach ($_SESSION["cart"] as $product_id => $product): ?>
<?php
$quantity = $product["quantity"];
$discount = ($quantity == 1) ? 0 : ($quantity == 2 ? 0.10 : 0.20);
$fullPrice = $product["quantity"] * $product["product_price"];
$discountAmount = $fullPrice * $discount;
$discountedPrice = $fullPrice - $discountAmount;
?>
<div id="top-cart" class="header-misc-icon d-none d-sm-block">
<a href="#" id="top-cart-trigger"><i class="uil uil-shopping-bag"></i><span class="top-cart-number"><?= $quantity; ?></span></a>
<div class="top-cart-content">
<div class="top-cart-title">
<h4>Shopping Cart</h4>
</div>
<div class="top-cart-items">
<div class="top-cart-item">
<div class="top-cart-item-image">
<a href="#"><img src="http://localhost/cpnag.ie/assets/images/shop/1.jpg" alt="Ad"></a>
</div>
<div class="top-cart-item-desc">
<div class="top-cart-item-desc-title">
<a href="#"><?= htmlspecialchars($product["product_name"]); ?></a>
<span class="top-cart-item-price d-block">€<?= number_format($fullPrice, 2); ?></span>
</div>
<div class="top-cart-item-quantity">x <?= $quantity; ?></div>
</div>
</div>
</div>
<div class="top-cart-action">
<span class="top-checkout-price">€<?= number_format($discountedPrice, 2); ?></span>
<a href="basket.php" class="button button-3d button-small m-0">Cart</a>
</div>
</div>
</div>
<?php endforeach; ?>
</header>
<!-- Content
============================================= -->
<section id="content">
<div class="content-wrap">
<div class="container clearfix">
<div class="row">
<div class="single-product">
<div class="product">
<div class="row gutter-40">
<div class="col-md-12 product-desc">
<div class="d-flex align-items-center justify-content-between">
<div class="product-price"><ins>€250.00</ins></div>
<?php if (!empty($_SESSION['cart'])): ?>
<form class="cart mb-0 d-flex justify-content-between align-items-center" action="basket.php" method="get">
<button type="submit" class="add-to-cart button m-0">View Cart</button>
</form>
<?php endif; ?>
</div>
<div class="line"></div>
<form class="cart mb-0 d-flex justify-content-between align-items-center" method="post">
<div class="quantity">
<input type="button" value="-" class="minus">
<input type="number" step="1" min="1" name="quantity" id="quantity" value="1" title="Qty" class="qty">
<input type="button" value="+" class="plus">
</div>
<button type="submit" name="add_to_cart" class="add-to-cart button m-0">Add to Cart</button>
</form>
</div>
<div class="w-100"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- JavaScripts
============================================= -->
<script src="assets/js/plugins.min.js"></script>
<script src="assets/js/functions.bundle.js"></script>
</body>
</html>
And this is my basket.phph code.
<?php
// view_cart.php
// Error checker
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Start or resume the session
session_start();
// Check if the cart array is not initialized in the session, initialize it
if (!isset($_SESSION["cart"])) {
$_SESSION["cart"] = [];
}
// Check if the "Clear Cart" button is clicked
if (isset($_POST["clear_cart"])) {
// Clear the cart
$_SESSION["cart"] = [];
}
// Check if the "Remove from Cart" button is clicked
if (isset($_POST["remove_from_cart"]) && isset($_POST["product_id"])) {
$productId = $_POST["product_id"];
// Decrease quantity by one for the selected product
if (isset($_SESSION["cart"][$productId])) {
$_SESSION["cart"][$productId]["quantity"]--;
// Remove the product from the cart if the quantity reaches zero
if ($_SESSION["cart"][$productId]["quantity"] <= 0) {
unset($_SESSION["cart"][$productId]);
}
}
}
// Check if the "Update Cart Quantity" button is clicked
if (isset($_POST["update_cart_quantity"]) && isset($_POST["product_id"]) && isset($_POST["quantity"])) {
$productId = $_POST["product_id"];
$quantity = intval($_POST["quantity"]);
// Update quantity for the selected product
if (isset($_SESSION["cart"][$productId])) {
$_SESSION["cart"][$productId]["quantity"] = $quantity;
}
}
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<!-- head code here -->
</head>
<body class="stretched">
<header id="header" class="header-size-sm" data-sticky-shrink="false">
<!-- Top Cart
============================================= -->
<?php foreach ($_SESSION["cart"] as $product_id => $product): ?>
<?php
$quantity = $product["quantity"];
$discount = ($quantity == 1) ? 0 : ($quantity == 2 ? 0.10 : 0.20);
$fullPrice = $product["quantity"] * $product["product_price"];
$discountAmount = $fullPrice * $discount;
$discountedPrice = $fullPrice - $discountAmount;
?>
<div id="top-cart" class="header-misc-icon d-none d-sm-block">
<a href="#" id="top-cart-trigger"><i class="uil uil-shopping-bag"></i><span class="top-cart-number"><?= $quantity; ?></span></a>
<div class="top-cart-content">
<div class="top-cart-title">
<h4>Shopping Cart</h4>
</div>
<div class="top-cart-items">
<div class="top-cart-item">
<div class="top-cart-item-image">
<a href="#"><img src="http://localhost/cpnag.ie/assets/images/shop/1.jpg" alt="Ad"></a>
</div>
<div class="top-cart-item-desc">
<div class="top-cart-item-desc-title">
<a href="#"><?= htmlspecialchars($product["product_name"]); ?></a>
<span class="top-cart-item-price d-block">€<?= number_format($fullPrice, 2); ?></span>
</div>
<div class="top-cart-item-quantity">x <?= $quantity; ?></div>
</div>
</div>
</div>
<div class="top-cart-action">
<span class="top-checkout-price">€<?= number_format($discountedPrice, 2); ?></span>
<a href="http://localhost/cpnag.ie/siopa/cisean.php" class="button button-3d button-small m-0">Cart</a>
</div>
</div>
</div>
<?php endforeach; ?>
</header>
<!-- Content
============================================= -->
<section id="content">
<div class="content-wrap">
<div class="container clearfix">
<div class="row">
<!-- View Cart Table
============================================= -->
<div class="col-12 pb-6">
<?php if (!empty($_SESSION["cart"])): ?>
<table class="table cart mb-5">
<thead>
<tr>
<th class="cart-product-remove"> </th>
<th class="cart-product-thumbnail"> </th>
<th class="cart-product-name">Name</th>
<th class="cart-product-price">Price</th>
<th class="cart-product-quantity">Quantity</th>
<th class="cart-product-fullprice">Total Cost</th>
<th class="cart-product-discount">Discount</th>
<th class="cart-product-subtotal">Discount Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($_SESSION["cart"] as $product_id => $product): ?>
<?php
$quantity = $product["quantity"];
$discount = ($quantity == 1) ? 0 : ($quantity == 2 ? 0.10 : 0.20);
$fullPrice = $product["quantity"] * $product["product_price"];
$discountAmount = $fullPrice * $discount;
$discountedPrice = $fullPrice - $discountAmount;
?>
<tr class="cart_item">
<td class="cart-product-remove">
<form action="" method="post" class="mb-0">
<input type="hidden" name="remove_from_cart" value="1">
<input type="hidden" name="product_id" value="">
<button type="submit" class="button button-mini button-circle button-border button-red remove-from-cart"><i class="fa-solid fa-trash me-0"></i></button>
</form>
</td>
<td class="cart-product-thumbnail"><img width="64" height="64" src="http://localhost/cpnag.ie/assets/images/shop/1.jpg" alt=""></td>
<td class="cart-product-name"><?= htmlspecialchars($product["product_name"]); ?></td>
<td class="cart-product-price"><span class="amount">€250</span></td>
<td class="cart-product-quantity">
<form action="" method="post" class="mb-0">
<div class="quantity">
<input type="hidden" name="update_cart_quantity" value="1">
<input type="hidden" name="product_id" value="<?= $product_id; ?>">
<input type="button" value="-" class="minus">
<input type="text" name="quantity" value="<?= $quantity; ?>" class="qty">
<input type="button" value="+" class="plus">
<button type="submit" class="button button-mini button-circle button-border button-red"><i class="bi-arrow-clockwise me-0"></i>Update</button>
</div>
</form>
</td>
<td class="cart-product-fullprice"><span class="amount">€<?= number_format($fullPrice, 2); ?></span></td>
<td class="cart-product-discount"><span class="amount">€<?= ($discount * 100) . '%'; ?></span></td>
<td class="cart-product-subtotal"><span class="amount color lead fw-medium">€<?= number_format($discountedPrice, 2); ?></span></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="row justify-content-between align-items-center py-2 col-mb-30">
<div class="col-lg-auto ps-lg-0">
<div class="row align-items-center">
<div class="col-md-4 mt-3 mt-md-0">
<form action="" method="post">
<button type="submit" name="clear_cart" class="clear-cart button">Clear Cart</button>
</form>
</div>
</div>
</div>
</div>
<?php else: ?>
<p>Your cart is empty. <a href="shop.php">Return to Shop</a></p>
<?php endif; ?>
</div>
</div>
</div>
</div>
</section>
<!-- JavaScripts
============================================= -->
<script src="http://localhost/cpnag.ie/assets/js/plugins.min.js"></script>
<script src="http://localhost/cpnag.ie/assets/js/functions.bundle.js"></script>
</body>
</html>