3

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.

3
  • 2
    you cannot write php code within script tags like that. Commented Jul 29, 2018 at 13:06
  • 2
    no, that won't work. You cannot call a php function (unset()) via javascript. It has to be a form submit or a ajax call to a php script that then unsets the item in the cart. Commented Jul 29, 2018 at 13:06
  • If you don't know PHP & Javascript, use a ready made solution, opencart is quite popular. Commented Jul 29, 2018 at 14:35

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for hellp but I have an error: Uncaught TypeError: Cannot read property 'remove' of null at removeItem ((index):163) at HTMLElement.onclick ((index):96)
It can't find the HTML element. Check if the element exists and if the ID is indeed set to the correct value. f you did the second part of my snippets the element with the id like id="single-cart-item-123" should be there. If you refresh the page now, is the item removed from the cart? If that is the case the AJAX - PHP part works at least. Then it is only the removal of the element that needs to be fixed.
I ajusted the PHP and JS part to add some checks.
Thanks for your effort, still doesn't work but I will recheck my code tommorow. In the meantime I flagged your answer as accepted.
@Florin let me know tomorrow. I will help you get it working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.