简体   繁体   English

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

[英]add to cart div refresh through Ajax

I am trying to add items in my cart through Ajax call. 我试图通过Ajax调用在购物车中添加商品。 I tried it doing simple just with php and it works fine. 我试着用php做简单的事情,它工作正常。 But now i am trying to convert my code for php+ajax. 但是现在我正在尝试将我的代码转换为php + ajax。 I have an index.php page in which i am dynamically changing my content. 我有一个index.php页面,我在其中动态更改内容。 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. 它将我重定向到这样的页面: index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1每次调用新页面时,页面都会通过$_GET命令传递。 I have a cart button on index.php header section.I want to refresh the div whose id is named as "cart". 我在index.php标头部分上有一个购物车按钮。我想刷新ID为“ cart”的div。 I am failing to do this through AJAX.Here i am pasting my code. 我无法通过AJAX执行此操作。在这里,我粘贴了我的代码。 Any suggestions or help will be appreciated. 任何建议或帮助,将不胜感激。

cart div 购物车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 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 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>

So, I'm assuming that your PHP code works and that the data is sent properly. 因此,我假设您的PHP代码有效且数据已正确发送。 I'm also assuming that your $.ajax call works. 我还假设您的$ .ajax调用有效。 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. 您应该能够简单地使用jQuery来更新div的数据。

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

Or if you want to process the data before hand. 或者,如果您想事先处理数据。

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

I am also assuming both the php and ajax codes work well... All you need do is store the current value state of the div by saying something like 我还假设php和ajax代码都可以正常工作...所有您需要做的就是通过说类似以下内容来存储div的当前值状态

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

and then appending the new result as 然后将新结果附加为

newv = oldv + responseMessage;

and finally saying 最后说

div.innerHTML=newv;

I believe this should work perfectly for your refresh request situation. 我相信这对于您的刷新请求情况应该是完美的。 You could adopt and adapt this idea in various conditions. 您可以在各种条件下采用和适应这种想法。

Note: I am also assuming that both the old and new values are either text/HTML contents not requiring any mathematical calculations 注意:我还假设新旧值都是文本/ HTML内容,不需要任何数学计算

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM