I have the following function in PHP which adds an item to a shopping cart every time the user clicks on Add to cart.
The issue is that, if someone reloads manually the page after having added an item to the cart, a new item gets added.
Any tips to avoid this?
function addtocart($pid,$q)
{
if($pid<1 or $q<1) return;
if(is_array($_SESSION['cart']))
{
$max=count($_SESSION['cart']);
$_SESSION['cart'][$max]['itemId']=$pid;
$_SESSION['cart'][$max]['qty']=$q;
$max=count($_SESSION['cart']);
}
else
{
$_SESSION['cart']=array();
$_SESSION['cart'][0]['itemId']=$pid;
$_SESSION['cart'][0]['qty']=$q;
$max=count($_SESSION['cart']);
}
}
This is how I call the function:
User clicks on add to cart:
<input type="button" value="<?php echo $lang['ADDTOCART']; ?>" class="addToCart" onclick="addtocart(<?php echo $itemId; ?>)" />
Javascript executed:
<script language="javascript">
function addtocart(pid){
document.cartAdding.itemId.value=pid;
document.cartAdding.command.value='add';
document.cartAdding.submit();
}
</script>
Page reloads and comes into here:
if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' && $_REQUEST['itemId']>0)
{
$pid=$_REQUEST['itemId'];
addtocart($pid,1);
}
Thanks