How can PHP and JavaScript work together to update a shopping cart dynamically in a web application?

To update a shopping cart dynamically in a web application, PHP can be used to handle the backend logic such as updating the cart items in the database, while JavaScript can be used to handle the frontend interactions like adding or removing items from the cart without reloading the page.

// PHP code to update the shopping cart dynamically
if(isset($_POST['item_id']) && isset($_POST['quantity'])){
    $item_id = $_POST['item_id'];
    $quantity = $_POST['quantity'];

    // Update the cart in the database based on the item_id and quantity
    // This is just a placeholder, actual implementation will depend on the database structure
    // For example, you could use SQL queries to update the cart table

    echo json_encode(['success' => true, 'message' => 'Cart updated successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}