How can PHP be used to add items to a shopping cart without reloading the current page?

To add items to a shopping cart without reloading the current page, you can use AJAX in combination with PHP. AJAX allows you to send a request to the server in the background without refreshing the page, and PHP can handle the request to add the item to the cart. You can then update the cart content on the page dynamically using JavaScript.

<?php

// Check if the request is made using AJAX
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    
    // Add item to the shopping cart
    $item_id = $_POST['item_id'];
    $quantity = $_POST['quantity'];
    
    // Add the item to the cart logic here
    
    // Return a success message
    echo json_encode(['status' => 'success', 'message' => 'Item added to cart']);
    
} else {
    // Handle non-AJAX requests here
    echo "Invalid request";
}

?>