将图标添加到购物车PHP / Jquery中添加的产品

时间:2016-11-21 19:13:26

标签: php jquery ajax

我正在尝试为已添加到购物车的商品添加复选标记。 我正在使用ajax返回。 但我知道我做错了。 我有点失落。 我先用php制作,它可以工作,但只有当我刷新页面时才会显示。 我的PHP代码...

if(isset($_SESSION['product'][$id])){
    $added='<a href="" class="badge-corner" product_id="'.$id.'" >
    <span class="fa fa-check"></span></a>';
    }else{
    $added='';
    }

我想使用ajax来显示复选标记。

enter image description here

这是我获取产品ID并将其存储到会话的地方。 我的添加到购物车功能和项目计数器代码..(cart_function2.php)

  <?php header('Content-Type: application/json');

session_start();
 if (isset($_GET['action'])) {

  $action = $_GET['action'];
  $prod   = $_GET['prod_id'];
  $result="";

  switch ($action) {

    case 'add':
        $result = add_prod($prod);
    break;

    default:
        $result = ['result'=>'error'];
    break;
  }



}
// Calculate subtotal here
$result['totals'] = new stdClass;
$total_in_cart=count($_SESSION['product']);  
$_SESSION['products']=$total_in_cart;
if(isset($_SESSION['product'][$prod])){
$added='<a href="" class="badge-corner" product_id="'.$prod.'"  ><span class="fa fa-check"></span></a>';
}else{
    $added='';
}

$result['added'] = $added;
$result['items'] =  $total_in_cart; 

 echo json_encode($result);

function add_prod($prod){
  //add function
$_SESSION['product'][$prod] = 1;
$_SESSION['products']++;

return ['result'=>'success'];
}



?>

这是我画廊中的剧本......

$('.actions').click(function(e){ 
  e.preventDefault(e);
  var action = $(this).attr('data-action'); //gets button id
  var id = $(this).attr('product_id');
  console.log("triggered action " + action + " for product " + id); 

  $.ajax({
  url: 'cart_functions2.php',
  type : 'GET',
  data: {action:action,prod_id:id},
  dataType: 'json'

}).done(function(data) {
    console.log("ajax call returned the following: " + JSON.stringify(data));

  if (data.result == "success") {

$("#items").html(data.items);
$(".show").html(data.added) + id;
//some debugging script

我想在这里显示

<div class="show">'.$added.'</div>

当我点击添加产品时,我的所有产品都会立即被检查。 为什么? 请帮助我,我仍然是jquery的菜鸟。

0 个答案:

没有答案