php – How to add product to shopping cart using ajax and hide add product button?

Question:

This is my PHP file, which allows me to add products to the cart:

<?php
session_start();

$itemId = isset($_GET['itemId']) ? $_GET['itemId'] : "";



if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['qtyupdate'])) {
    for ($i = 0; $i < count($_POST['qtyupdate']); $i++) {
        $key = $_POST['arr_key_' . $i];
        $_SESSION['qty'][$key] = $_POST['qtyupdate'][$i];
    }

} else {
    $qty = isset($_POST['qty']) ? $_POST['qty'] : 1;
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
        $_SESSION['qty'][] = array();
    }
    if (in_array($itemId, $_SESSION['cart'])) {
        $key = array_search($itemId, $_SESSION['cart']);
        $_SESSION['qty'][$key] = $_SESSION['qty'][$key] + $qty;
    } else {
        array_push($_SESSION['cart'], $itemId);
        $key = array_search($itemId, $_SESSION['cart']);
        $_SESSION['qty'][$key] = $qty;
    }
}
header('location:cart.php');

?>

The button I have to add products is the same that I would like to hide for other information when that product is already added to the shopping cart:

<div class="buy-now">
    <a href="../updatecart.php?itemId=11">Buy now</a>
</div>

The other information to show:

<div class="buy-now">
    <span>Producto ya añadido</span>
</div>

Answer:

The $_SESSION['cart'] variable is an array where you store the products that you already have added to the cart

then:

//negamos la busqueda
if (!in_array($itemId, $_SESSION['cart'])) {
        echo "
          <div class='buy-now'>
              <a href='../updatecart.php?itemId=11'>Buy now</a>
          </div>
          ";
    } else {
        echo "
        <div class='buy-now'>
            <span>Producto ya añadido</span>
        </div>
        ";
    }
Scroll to Top