簡體   English   中英

通過Ajax添加到購物車div刷新

[英]add to cart div refresh through Ajax

我試圖通過Ajax調用在購物車中添加商品。 我試着用php做簡單的事情,它工作正常。 但是現在我正在嘗試將我的代碼轉換為php + ajax。 我有一個index.php頁面,我在其中動態更改內容。 當我單擊一些導航列表時。 它將我重定向到這樣的頁面: index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1每次調用新頁面時,頁面都會通過$_GET命令傳遞。 我在index.php標頭部分上有一個購物車按鈕。我想刷新ID為“ cart”的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);

    }

}
}
?>

阿賈克斯

<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>

因此,我假設您的PHP代碼有效且數據已正確發送。 我還假設您的$ .ajax調用有效。 如果其中之一不正確,請告訴我。

您應該能夠簡單地使用jQuery來更新div的數據。

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

或者,如果您想事先處理數據。

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

我還假設php和ajax代碼都可以正常工作...所有您需要做的就是通過說類似以下內容來存儲div的當前值狀態

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

然后將新結果附加為

newv = oldv + responseMessage;

最后說

div.innerHTML=newv;

我相信這對於您的刷新請求情況應該是完美的。 您可以在各種條件下采用和適應這種想法。

注意:我還假設新舊值都是文本/ HTML內容,不需要任何數學計算

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM