I'm developing a dropdown shopping cart using php in the server side and JS in the front end. I have 2 functions that only work once. One is to avoid closing the dropdown shopping cart if the mouse is clicked inside of it, and the other erases a selected item via ajax. The function that avoids closing the window when clicked inside works well the first time but the function that deletes the item selected, works but doesn't refresh the div where the shopping cart is. After that first interaction, non of both functions work anymore until I refresh the page. Any help is welcome.
This is the button that should delete the item (programmed in php) :
<script>
$(document).ready(function(){
$('.container .dropdown-cart').on('click',function(e) {
e.stopPropagation();
});
});
</script>
<!-- delete item selected from shopping cart -->
<script>
$(document).ready(function(){
$('.item_delete').on('click', function () {
var item_id = $(this).attr("cart_item");
$.ajax({
url:"delete_online_item.php",
method:"POST",
data:{item_id:item_id},
dataType:"json",
success:function(data){
$('#shopping_cart').html(data);
}
});
});
});
</script>
Edition:
I'm not sure to what selector should I bind it. Here is the what refreshes the shopping cart which is called in the navbar:
<div id="shopping_cart" class="float-right cart-nav nav-item">
<?php include ("shopping_cart.php"); ?>
</div>
And this is the program where the shopping dropdown is generated dynamically (shopping_cart.php):
<div class="dropdown">
<a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="ion-ios-cart"></i><span class="badge badge-primary"><?php echo $disp_num_items; ?></span></a>
<ul class="dropdown-menu dropdown-menu-right dropdown-cart">
<li>
<ul class="list-unstyled">
<?php
/* shopping cart dropdown */
if(empty($_SESSION["cart"])) {
echo '<li class="clearfix text-center">';
echo '<h4 class="text-danger">Empty Cart</h4>';
echo '</li>';
} else {
$output = "";
$gtotal = 0;
foreach ($_SESSION["cart"] as $i => $key) {
echo '<li class="clearfix">';
echo '<div class="oHidden">';
//echo '<span id="item_delete" cart_item="' . $i . '"><i class="ion-ios-close-outline"></i></span>';
echo '<button type="button" class="item_delete" cart_item="' . $i . '"><i class="ion-ios-close-outline"></i></button>';
echo '<h4>' . $_SESSION['cart'][$i]['name'] . '</h4>';
echo '<p class="text-white-gray">' . $_SESSION['cart'][$i]['amount'] . '</strong></p>';
echo '</div>';
echo '</li>';
}
/* display total in shopping cart dropdown */
echo '<li class="clearfix">';
echo '<div class="float-right">';
echo '<a href="#" class="btn btn-primary">Checkout</a>';
echo '</div>';
echo '<h4>';
echo '<small>Subtotal - </small> $$$$';
echo '</h4>';
echo '</li>';
}
?>
</ul>
</li>
</ul>