I'm trying to remove an item from a sort of shopping cart. The items are saved to a session when they are "saved to the shopping cart".
But now I would like to be able to remove certain items from this "shopping cart". Because I got the script from here (stackoverflow) I'm not that familiar with the code. I saw some answers on google and here that described using unset
to delete the entry from the session. But I wouldn't know where to start with this one. If additional information is needed please let me know. Thanks for having a look at my question...
Here is the HTML (nothing special):
<div class="txtHint"></div>
This is my script:
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('example.com/reload.php', {productName: productName}, function(data) {
$('.txtHint').html(data);
})
});
This is my reload.php file:
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Saved Items</h4>
<?php foreach ($_SESSION['products'] as $product): ?>
<div class="echo-product"><i style="color:#F60;padding-right:20px;" class="fa fa-anchor" aria-hidden="true"></i><?php echo htmlspecialchars($product); ?></div>
<?php endforeach;?>
Updated code: As suggested by Bert Maurau (I Hope).
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['products'][$productName]);
}
if(isset($_GET['addparam'])){
$_SESSION['products'][] = $productName;
}
?>
If I use this it doesn't add any new items...