【问题标题】:add to cart div refresh through Ajax通过 Ajax 添加到购物车 div 刷新
【发布时间】:2015-12-11 19:21:08
【问题描述】:

我正在尝试通过 Ajax 调用在我的购物车中添加商品。我试过用 php 做简单的事情,效果很好。但现在我正在尝试将我的代码转换为 php+ajax。我有一个index.php 页面,我在其中动态更改我的内容。当我点击一些导航列表时。它会将我重定向到这样的页面:index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1 每次调用新页面时页面都会通过$_GET 命令传递。我在index.php 标题部分有一个购物车按钮。我想刷新 id 名为“购物车”的 div。我没有通过 AJAX 做到这一点。我在这里粘贴我的代码。任何建议或帮助将不胜感激。

购物车 div

    <div id="cart">
    <li style="color: #515151">
    <img id="cart_img" src="images/cart.png">
     Cart <span class='badge' id='comparison-count'>
     <?php
     if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
    {
      $cart_count=count($_SESSION['cart']);
       echo $cart_count;
     }
      else {
      $cart_count=0;
     echo $cart_count;
      }
       ?>
      </span>
       </li>
      </div>

item.php

<div>
<?php
$query=mysqli_query($con,"select * from products where cat_id='$cat_id' and s_cat_id='$s_cat_id' ORDER BY product_name ASC");
if(mysqli_num_rows($query)!=0){
while($row=mysqli_fetch_assoc($query)){
?>
<div>
<input type="hidden" id="pid" value="<?php echo $row['productid'] ?>">
 <h4><?php echo $row['product_name']; ?></h4>
 <h4>Price<?php echo "$" . $row['product_price']; ?> </h4>
 <form  method="post" action="">
 <input type="hidden" id="page" name="page" value="items">
<input type="hidden" id="action" name="action" value="add">
<input type="hidden" id="id" name="id" value="<?php echo $row['productid']; ?>">
<input type="hidden" id="name" name="name" value="<?php echo $row['product_name']; ?>">
<input type="hidden" id="cat_id" name="cat_id" value="<?php echo $row['cat_id']; ?>">
 <input type="hidden" id="s_cat_id" name="s_cat_id" value="<?php echo $row['s_cat_id']; ?>">
 <input type="hidden" id="category" name="category" value="<?php echo $cat ?>">
<td>Colors:
 <select name="color" id="color">
 <option selected value="choose">choose</option>
 <option value="blue" id="blue">Red</option>
 <option value="blue" id="blue">Blue</option>
 <option value="yellow" id="yellow">Yellow</option>
  <option value="green" id="green">Green</option>
 </select></td>
  <td>Size : <select name="size" id="size"><option selected value="Choose size">Choose</option>
  <option value="XL" id="XL">XL</option>
  <option value="L" id="L">L</option></select>
  </td>
 </div>
<input type="submit" class="add-to-cart" id="addtocart" value="Add to Cart">
</form>
 </div>
 </div>

add_cart.php

   <?php
include ("db/db.php");
session_start();
if($_POST){
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
            array(
                'type'=>'error',
                'text' => 'Request must come from Ajax'
            ));

        die($output);
    }
if(isset($_POST['Action']) && $_POST['Action']=="add" && isset($_POST['S_cat_id']) && isset($_POST['Cat_id']) ){

    $id=intval($_POST['Id']);
    $size = $_POST['Size'];
    $color = $_POST['Color'];
    $sql="SELECT * FROM products WHERE productid={$id}";
    $data = mysqli_query($con,$sql);
    if (mysqli_num_rows($data) == 1)
    {
        $row = mysqli_fetch_array($data);
        $index = $id." ".$color. " ".$size;
        if( isset($_SESSION['cart'][$index]) && isset($_SESSION['cart'][$index]['color']) && $_SESSION['cart'][$index]['color'] == $color && isset($_SESSION['cart'][$index]['size']) && $_SESSION['cart'][$index]['size'] == $size){
            $_SESSION['cart'][$index]['quantity']++;
            $output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
            die($output);

        }else{
            $_SESSION['cart'][$index] = array('quantity' => 1,'id'=> $id, 'price' => $row['product_price'],  'size' => $size, 'color' => $color, 'name' => $row['product_name']);
            $output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
            die($output);

        }
    }

    else{
        $message="Product ID is invalid";
        $output = json_encode(array('type'=>'error', 'text' => $message));
        die($output);

    }

}
}
?>

Ajax

<script>
    $(document).ready(function() {

        $('#addtocart').click(function(e){
            e.preventDefault();

            var  page = $("#page").val(),
                action = $("#action").val(),
                name= $("#name").val(),
                cat_id= $("#cat_id").val(),
                s_cat_id = $("#s_cat_id").val(),
                id=$("#id").val(),
                color=$("#color").val(),
                size=$("#size").val(),
                category = $("#category").val();


            var proceed = true;
            if(proceed){

                post_data= { 'Page': page, 'Action': action,'Name': name, 'Cat_id': cat_id,'S_cat_id':s_cat_id, 'Category': category,'Id':id,'Color':color,'Size':size};
                $.post('add_cart.php', post_data, function(response){

                    //load json data from server and output message
                    if(response.type == 'error')
                    {

                        //output=$('.alert-error').html(response.text);

                    }else{

                        output= $("#cart").load();

                    }

                    $(".alert-error").delay(3200).fadeOut(300);
                }, 'json');
            }


        });

    });
</script>

【问题讨论】:

    标签: javascript php jquery html ajax


    【解决方案1】:

    所以,我假设您的 PHP 代码可以正常工作并且数据已正确发送。我还假设您的 $.ajax 调用有效。如果其中一项不正确,请告诉我。

    你应该可以简单地使用 jQuery 来更新 div 的数据。

    $("some div").html = response.text;
    

    或者,如果您想事先处理数据。

    $("some div").html = process(response.text);
    

    【讨论】:

    • 你已经假设这两个事情是一致的。但是您提供的代码是替换 div 中我不需要的 html。我只需要刷新整个div。因为其中有count() 函数,它将刷新计数器徽章。
    • “刷新 div”是什么意思,你能重新运行你的计数函数吗?
    【解决方案2】:

    我还假设 php 和 ajax 代码都运行良好... 您需要做的就是存储 div 的当前值状态,例如

    div=document.getElementById('elem_id'); oldv = div.firstChild.nodeValue;

    然后将新结果附加为

    newv = oldv + responseMessage;

    最后说

    div.innerHTML=newv;

    我相信这应该非常适合您的刷新请求情况。您可以在各种情况下采用和调整这个想法。

    注意:我还假设旧值和新值都是不需要任何数学计算的文本/HTML 内容

    【讨论】:

      猜你喜欢
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 2018-05-27
      • 2018-08-26
      • 2019-10-02
      • 2015-10-11
      • 1970-01-01
      相关资源
      最近更新 更多