Can anyone see why my variable $unit_price isn't updating (in fact it isn't even being applied to the session variable) in this code (it must be something simple but I can't see it and is driving me mad). I have tested the posted data and it is being sent through and all other posted variables are being added to the session.
Please note that this is also using jQuery and Ajax.
My form:
<form method="#" class="cart">
<input type="hidden" name="item_id" value="prods_<?php echo $product['prodid'];?>" />
<input type="hidden" name="unit_price" value="<?php echo $product['prod_price'];?>" />
<input type="hidden" name="item_name" value="<?php echo $product['prod_name'];?>" />
<input type="hidden" name="item_qty" value="1"/>
<input type="hidden" name="item_url" value="https://www.uniteddiesel.co.uk/diesel-products.php?prod_id=<?php echo $product['prodid']; ?>/"/>
<input type="submit" class="rounded-buttons" name="add_to_bag" value="Add to Bag" />
<a href="diesel-products.php?prod_id=<?php echo $product['prodid']; ?>/"><input type="button" class="rounded-buttons" name="view" value="View" /></a>
</form>
My jQuery / Ajax:
$('.cart').submit(function (e) {
e.preventDefault();
// validate form
$.ajax({
cache: false,
url: 'inc/shopping_bag.php',
data: $('form.cart').serialize() + '&action=send',
type: 'POST',
success: function(html) {
$('#shopping-bag p').html(html);
}
});
});
My PHP (sorry it's a bit long):
<?php
require_once("../includes/config.php");
//Check if the basket array exists or not
if (!is_array($_SESSION['basket']))
{
$_SESSION['basket']=array();
}
if (!empty($_POST['item_id'])) {
$item_id=$_POST['item_id'];
}
$item_qty=ceil($_POST['item_qty']); // CEIL is to stop partial quantities (0.01 etc)
$unit_price=$_POST['unit_price'];
$item_name = $_POST['item_name'];
$item_url = $_POST['item_url'];
$match=0;
$count=0;
if($item_qty>0)
{
//Where ids match, add the qty to the existing qty
if (is_array($_SESSION['basket']))
{
foreach ($_SESSION['basket'] as $array)
{
if ($array['item_id']==$item_id)
{
$match=1;
$array['item_qty']+=$item_qty;
$_SESSION['basket'][$count]=$array;
}
$count++;
}
}
//If we did not find a match, add the item to the array
if ($match==0)
{
$array=array();
$array['item_id']=$item_id;
$array['item_qty']=$item_qty;
$array['unit_price']=$unit_price;
$array['item_name']=$item_name;
$array['item_url']=$item_url;
//Add to the existing basket contents
$_SESSION['basket'][]=$array;
}
}
if (is_array($_SESSION['basket']))
{
$total=0;
$totalItems=0;
foreach ($_SESSION['basket'] as $array)
{
$totalItems+=$array['item_qty'];
$cost=$array['item_qty']*$array['unit_price'];
$total+=$cost;
}
echo 'Shopping Bag<br>'.$totalItems.' Items<br />£'.sprintf("%01.2f", $total);
}
else {
echo 'Shopping Bag<br>0 Items<br />£0.00';
}
?>
Can anyone see what is wrong (only a problem with the unit_price)??