views:

97

answers:

2

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

+1  A: 

The most simple way is to use json_encode() on the variable. so...

header('Content-type: text/javascript; charset=UTF-8'); // or what ever charset you're using
echo json_encode($productData);

then you can just read the values in responseText as:

alert(responseText.whatever);
arnorhs
Thank you arnorhs. My firebug shows the response text with the value I want, but I don't know how to get it from your alert(responseText.whatever)... "whatever" means productData?
Jerry
responseText (should be called responseJson) will be your json productData object, or whatever you throw into the json_encode() function
arnorhs
@Jerry: If you use `eval(responseText)`, it will convert it into a JS array. I.e.: `var data = eval(responseText); alert(data[0]);`
mattbasta
Got you. Thanks a lot matt!
Jerry
If your dataType in the ajax request is set to 'json', you shouldn't have to call eval() on the responseText variable. It should've been a JS object already
arnorhs
A: 

I don't know if this helps, but what if you return false in the link.

<a class="addToCart" href="javascript:void(0)" onclick="addToCart(<?php echo $productId?>); return false;">

Returning false will mean that the browser will not follow the link. That way the document wont reload.

Aaron