I have created an add to cart code using session and jquery. It's almost done but I am getting two issues.
1) When I refresh the page, I am getting error
Notice: Undefined index: quantity in C:\xampp\htdocs\add-to-cart\ajax_cart.php on line 5
2) I am able to add the product to the cart but If I add the same product two times then I am getting the error.
Notice: Undefined index: 250.00 in C:\xampp\htdocs\add-to-cart\ajax_cart.php on line 30
Notice: Undefined offset: 1 in C:\xampp\htdocs\add-to-cart\ajax_cart.php on line 31
There is some issue with else part (might be the price).
else{
$_SESSION['product_cart'][$product_id][$product_price] = $_SESSION['product_cart'][$product_id][$product_price] + ($product_price*$quantity);
$_SESSION['product_cart'][$product_id][$quantity] = $_SESSION['product_cart'][$product_id][$quantity]+$quantity;
}
AJAX function to call the ajax_cart.php
function add_cart(p_id=""){
var quantity = $(".quantity"+p_id).val();
$.ajax({
type:"post",
url:"ajax_cart.php",
data:{action:'add',p_id:p_id,quantity:quantity},
success:function(result){
$('.cart_data').html(result);
}
});
}
Add to Cart
$action = $_POST['action'];
$p_id = trim($_POST['p_id']);
$quantity = $_POST['quantity'];
if($action == 'add'){
if(!empty($p_id)){
$query = "SELECT product_id,product_title,product_price,product_image FROM product WHERE product_id=?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("i", $p_id);
$stmt->execute();
$stmt->bind_result($product_id, $product_title,$product_price, $product_image);
$stmt->fetch();
}
$product = array(
"p_id"=>$product_id,
"title"=>$product_title,
"price"=>$product_price*$quantity,
"image"=>$product_image,
"quantity"=>$quantity
);
if(isset($_SESSION['product_cart']) && !empty($_SESSION['product_cart']))
{
if(!array_key_exists($product_id,$_SESSION['product_cart']))
{
$_SESSION['product_cart'][$product_id] = $product;
}
else{
$_SESSION['product_cart'][$product_id][$product_price] = $_SESSION['product_cart'][$product_id][$product_price] + ($product_price*$quantity);
$_SESSION['product_cart'][$product_id][$quantity] = $_SESSION['product_cart'][$product_id][$quantity]+$quantity;
}
}
else{
$_SESSION['product_cart'][$product_id] = $product;
}
}
}