Hi All, I am trying to build a shopping cart site. When a user click add to cart image on the product page, The product title will show a "The product is in your cart" text without reloading the page. I am using session and ajax but no luck so far. I appreciate any helps.
My html cold
<table id="<?php echo $productId; ?>" width="594" border="0" cellpadding="5" cellspacing="0">
<tr>
<td><img src="<?php echo "$brandImage"; ?></td>
<td <?php echo $productName; ?> //The "The product is in your cart" will be showed here</td>
</tr>
<tr>
<td><a class="addToCart" href="javascript:void(0);" onclick="addToCart(<?php echo $productId?>)">
</td>
My Javascript file (addToCart.js)
function addToCart(productId){
var url="addToCart.php";
url=url+"?productId="+productId;
url=url+"&sid="+Math.random();
$.post(
url,
function(responseText){
alert(responseText); //I wish I can get productData value from addToCart.php
},
"html"
)
My php file (addToCart.php)
<?php SESSION_START();
$productId=$_GET['productId'];
$cart=$_SESSION['cart'];
if(isset($cart)){
$cart.=",".$productId;
$product=explode(',',$cart);
$totalItem=count($product);
}else{
$cart=$productId;
$totalItem=1;
};
$productData=array();
foreach($product as $id){
$productData[$id]=(isset($productData[$id])) ? $productData[$id]+1 :1;
};
$_SESSION['cart']=$cart;
//print_r($productData);
echo $productData; //Not sure what to do to send $productData back to my addToCart.js variable
?>
I tried to make the code look simple. Any suggestion will be a great help. Thanks