简体   繁体   中英

Combine PHP with Javascript to remove item from cart

I'm building an online store for my sister and i'm struggling with removing specific item from cart ( $_SESSION ) when I click the X icon of product ( onclick="") .

<?php
  if (empty($_SESSION['cart'])) {
      $_SESSION['cart'] = array();
  }
?>

<div class="cart-content d-flex">

<!-- Cart List Area -->
<div class="cart-list">

    <?php
    $subtotal = 0;
    $livrare = 17;
    $subtotal_modif = 0 . " Lei";
    $object = new Produs();

    $cartItems = $_SESSION['cart'];

    foreach ($cartItems as $item):
    $rows = $object->getRows("SELECT * FROM produs");

    foreach ($rows as $row) {
        //$subtotal += $row['pret_produs'];

    if ($item['id'] == $row['id_produs']) {
        $imagini = $object->getRows("SELECT * FROM imagini WHERE id_produs_imagine = ? LIMIT 1", [$row['id_produs']]);

        $pret = $row['pret_produs'];
        $pret_modif = str_replace('.', ',', $row['pret_produs']) . " LEI";
        $pret_vechi = $row['pret_vechi_produs'];
        $pret_redus_modif = str_replace('.', ',', $row['pret_vechi_produs']) . " LEI";

        $subtotal = $subtotal + ($pret * $item['cantitate']);
        $subtotal_modif = str_replace('.', ',', $subtotal) . " LEI";
    ?>


    <!-- Single Cart Item -->
    <div class="single-cart-item">
        <a href="#" class="product-image">
            <?php foreach ($imagini as $img) {

            echo '<img src="'. $object->photoPath() . $img['nume_imagine'] .'" alt="">';
            } ?>
            <!-- Cart Item Desc -->
            **<div class="cart-item-desc">
                <span class="product-remove"><i onclick="removeItem('<?php $item['id']; ?>')" class="fa fa-close" aria-hidden="true"></i></span>**

                <!-- <span class="badge">Mango</span> -->

                <h6><?php echo $row['nume_produs']; ?></h6>
                <p class="size">Marime: <?php echo $item['marime']; ?></p>
                <p class="color">Cantitate: <?php echo $item['cantitate']; ?></p>
                <p class="price"><?php echo $pret; ?></p>
            </div>
        </a>
    </div>
    <?php } }
    endforeach;
    ?>

</div>

I'm thinking in doing something like this at the end of page but I don't know how to do it properly:

<script>
    function removeItem(itemID) {
        <?php unset($_SESSION['cart']['<script>itemID</script>']); ?>
    }
</script>

I dont know how to combine PHP and JavaScript.

You can put this in the top of your PHP script:

if ( empty( $_SESSION['cart'] ) ) {
    $_SESSION['cart'] = [];
}

if ( isset( $_POST['remove_item'] ) ) {
    $itemID = $_POST['remove_item'];
    if ( isset( $_SESSION['cart'][ $itemID ] ) ) {
        unset( $_SESSION['cart'][ $itemID ] );
    }

    echo $itemID;
    die();
}

// THE REST OF YOUR PHP CODE.

Give the container of the item a unique id based on the item's id:

<div class="single-cart-item" id="single-cart-item-<?php echo $item['id']; ?>">
    <!-- --------------- -->
</div>

And this in your JS:

<script type="text/javascript">

    function removeItem( itemID ) {

        // make AJAX request to server to remove item from session.
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "cart.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("remove_item=" + itemID);
        xhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                var element = document.getElementById("single-cart-item-" + this.responseText);
                if (element !== null) {
                    element.remove();
                }
            }
        };



    }

</script>

The function removeItem( itemID ) is making an AJAX call to your PHP script. It passes the item ID as a POST value. Replace cart.php with the correct path (URL to your cart page).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM