I'm creating a cart page using PHP. I have managed to store the items that the person wants to buy in a session variable which stores an associative array that has the identifier of the item as the key and the quantity of the items as the value:
if (isset($_POST["btnSubmit"])){
$_SESSION["cart"][$isbn] += 1;
header("Location:cart.php");
}
I also managed to list these items on the cart using a foreach loop and a query:
<?php
$total;
foreach($_SESSION["cart"] as $product=>$quantity){
$query = mysqli_query($con,"SELECT * FROM BOOKS WHERE $product LIKE isbn");
$data = mysqli_fetch_array($query, MYSQLI_ASSOC);
$title = $data["title"];
$price = $data["price"];
$image = $data["image"];
$author = $data["author"];
$isbn = $data["isbn"];
print
"<a href='product.php?product=".$isbn."' class='list-group-item list-group-item-action>
<img src='".$image.">
<h5>".$title."</h5>
<h5>£".$price."</h5>
</a>
<select name='quant' id='quant'>
<option value=''>".$quantity."</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
</select>";
$total += $price*$quantity;
}
?>
As you can see, there is a dropdown list that I want to use to modify the number of items purchased. I need this list to update the value of the specific key within the $_SESSION['cart'] variable and then for that quantity to dynamically multiply by the price to display a total. For this, I am using jQuery.
<script>
$(document).ready(function(){
$("#quant").change(function(){
$.get('ajax/getTotal.php',{quant:$(this).val()},function(data){
$('#total').load(data);
});
});
});
</script>
I need to know two things:
- How do I update the values in the SESSION variable without affecting the other values?
- How do I properly use jQuery to dynamically update the total after the values in the SESSION variable have been updated?
I really appreciate your help. I'm really new to AJAX and I am very lost.