How can JavaScript be utilized to dynamically update item quantities in a PHP shopping cart?

To dynamically update item quantities in a PHP shopping cart using JavaScript, you can create an AJAX request that sends the updated quantity to a PHP script on the server. The PHP script will then update the session or database with the new quantity. Finally, you can use JavaScript to update the quantity displayed on the page without needing to refresh the entire page.

<?php
// Update item quantity in shopping cart
if(isset($_POST['item_id']) && isset($_POST['quantity'])) {
    $item_id = $_POST['item_id'];
    $quantity = $_POST['quantity'];

    // Update the quantity in the session or database
    // For example, if using sessions:
    $_SESSION['cart'][$item_id]['quantity'] = $quantity;

    // Send a response back to JavaScript
    echo json_encode(['success' => true]);
}
?>