dps43378 2015-12-11 19:21 采纳率: 0%
浏览 241

通过Ajax添加到购物车div刷新

I am trying to add items in my cart through Ajax call. I tried it doing simple just with php and it works fine. But now i am trying to convert my code for php+ajax. I have an index.php page in which i am dynamically changing my content. When i click on some nav list. It redirects me to page like this: index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1 where page is passed through $_GET command every time a new page is called. I have a cart button on index.php header section.I want to refresh the div whose id is named as "cart". I am failing to do this through AJAX.Here i am pasting my code. Any suggestions or help will be appreciated.

cart 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>
  • 写回答

2条回答 默认 最新

  • dongtazu3080 2015-12-11 21:21
    关注

    So, I'm assuming that your PHP code works and that the data is sent properly. I'm also assuming that your $.ajax call works. If one of these isn't true let me know.

    You should be able to simply use jQuery to update the data of the div.

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

    Or if you want to process the data before hand.

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

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致