2017-08-25 73 views
1

我正在做一個ajax調用,並用jQuery渲染出購物車。第二次Ajax調用後不值得刷新

function show_cart() { 

    $.ajax({ 
     url: 'functions/show-cart.php', 
     type: 'POST', 
     dataType: 'json', 
    }) 

    .done(function (data) { 
     $.each(data.cart, function (index, item) { 

      var showCart = ` 

       <div class="row hr marg-b-30 marg-t-30"> 
         <div class="col-md-2 col-sm-2 col-xs-12 marg-b-30"> 
          <img src="uploads/${item.pic_name}" alt="${item.product_name}" class=""> 
         </div> 
         <div class="col-md-5 col-sm-5 col-xs-12 marg-b-30"> 
          <a href="#" class=""><b>Product</b></a><b class="right">R${item.price}</b> 
          <p class="">${item.product_name}</p> 
          <button class="btn btn-xs bg-color--second removeItem" data-id="${item.item_id}" data-itr="${item.i}">Remove <i class="material-icons">delete</i></button> 

         </div> 
         <div class="col-md-3 col-sm-3 col-xs-12 marg-b-30"> 
          <div class="input input-counter"> 
           <div class="input__helper pos-left pointer input-counter__plus cartPlus" data-itr="{$i}"> 
            <i class="material-icons ico-xs"></i> 
           </div> 
           <input type="text" class="text-center" readonly="" value="${item.each_item}"> 
           <div class="input__helper pointer input-counter__minus"> 
            <i class="material-icons ico-xs"></i> 
           </div> 
          </div> 
         </div> 
         <div class="col-md-2 col-sm-2 col-xs-12 marg-b-30 text-right text-left-xs"> 
          <span class="price-xs">R${item.subtotal}</span> 
         </div> 
        </div>`; 

      $(".somediv").append(showCart); 


     }); 

     $("#total").append(data.total); 
     $("#subtotal").append(data.total); 


    }) 

    .fail(function (jqXHR, textStatus, errorThrown) { 
     console.log(textStatus + ': ' + errorThrown); 
     console.warn(jqXHR.responseText); 
    }); 
} 

購物車中的每個項目都有它的一個刪除/刪除按鈕,當用戶點擊的是,它要求我刪除功能,從購物車(淡出)刪除該項目。然後,我會調用相同的show-cart.php腳本的ajax調用,最初顯示購物車希望這會更新小計和總值,但它們與刪除購物車項目之前保持一致。我怎樣才能讓總數更新?

這裏是刪除項目或購物車功能刪除:

function remove_item() { 

    $("body").on("click", ".removeItem", function() { 
     var id = $(this).data('id'); 
     var indexToRemove = $(this).data('itr'); 
     var div = $(this).parents("div.hr"); 
     $.ajax({ 
      url: 'functions/show-cart.php', 
      type: 'POST', 
      dataType: 'json', 
      data: { 
       indexToRemove: indexToRemove 
      }, 
      beforeSend: function() { 
       $(div).html("<img src='images/spinner.gif'>"); 
       $("#total").empty(); 
      }, 
     }) 

     .done(function (data) { 
      $(div).fadeOut(); 
      $("#total").html(data.total);//This gives me the same total as before I removed the item 

     }) 

     .fail(function (jqXHR, textStatus, errorThrown) { 
      console.log(textStatus + ': ' + errorThrown); 
      console.warn(jqXHR.responseText); 
     }) 
    }) 
} // END REMOVE ITEM 

顯示,cart.php

if(!isset($_SESSION['cart_array'])) { 

    $itemsInCart = 0; 

} else { 

     $featured = "Yes"; 
     $cartTotal = ""; 
     $i=0; 
     foreach($_SESSION['cart_array'] as $each_item) { 
      $item_id = $each_item['item_id']; 

      $stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?"); 
      $stmt->bind_param("is", $item_id, $featured); 
      $stmt->execute(); 
      $result = $stmt->get_result(); 
      $numRows = $result->num_rows; 
      if($numRows > 0) { 
       while($row = $result->fetch_assoc()) { 
        $product_name = sanitize($row['product_name']); 
        $price = sanitize(money_format('%.2n', $row['price'])); 
        $subtotal = money_format('%.2n', $each_item['quantity'] * $price); 
        $pic_name = $row['pic_name']; 
        $cartTotal = $subtotal + $cartTotal; 
        $quantity = $each_item['quantity']; 

        $cart_details[] = array(

        "product_name" => $product_name, 
        "price" => $price, 
        "subtotal" => $subtotal, 
        "pic_name" => $pic_name, 
        "each_item" => $quantity, 
        "subtotal" => $subtotal, 
        "item_id" =>$item_id, 
        "i" => $i 

        ); 

        $i++; 
       } 
      } 

      $stmt->close(); 
     } 



    $response['total'] = $cartTotal; 
    $response['cart'] = $cart_details; 
    echo json_encode($response); 
} 


if(isset($_POST['indexToRemove']) && $_POST['indexToRemove'] !== "") { 

     $key_to_remove = $_POST['indexToRemove']; 
     if(count($_SESSION['cart_array']) <=1) { 
      unset($_SESSION['cart_array']); 
     } else { 

      unset($_SESSION['cart_array']["$key_to_remove"]); 
      sort($_SESSION['cart_array']); 
     } 
    } 
+0

你從哪裏得到這個'data'返回'show-cart.php'?從數據庫? –

+0

是的,產品ID用於從數據庫中獲取產品信息的其餘部分。 – user8463989

+0

你嘗試過'在console.log(data.total)'在Ajax做回調?它改變? –

回答

0

,你應該從會議上未設置項目返回Ajax響應之前。試試這個:

if(isset($_POST['indexToRemove']) && $_POST['indexToRemove'] !== "") { 

      $key_to_remove = $_POST['indexToRemove']; 
      if(count($_SESSION['cart_array']) <=1) { 
       unset($_SESSION['cart_array']); 
      } else { 

       unset($_SESSION['cart_array']["$key_to_remove"]); 
       sort($_SESSION['cart_array']); 
      } 
     }  

if(!isset($_SESSION['cart_array'])) { 

     $itemsInCart = 0; 
     $response['total'] = 0; 
     echo json_encode($response); 

    } else { 

      $featured = "Yes"; 
      $cartTotal = ""; 
      $i=0; 
      foreach($_SESSION['cart_array'] as $each_item) { 
       $item_id = $each_item['item_id']; 

       $stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?"); 
       $stmt->bind_param("is", $item_id, $featured); 
       $stmt->execute(); 
       $result = $stmt->get_result(); 
       $numRows = $result->num_rows; 
       if($numRows > 0) { 
        while($row = $result->fetch_assoc()) { 
         $product_name = sanitize($row['product_name']); 
         $price = sanitize(money_format('%.2n', $row['price'])); 
         $subtotal = money_format('%.2n', $each_item['quantity'] * $price); 
         $pic_name = $row['pic_name']; 
         $cartTotal = $subtotal + $cartTotal; 
         $quantity = $each_item['quantity']; 

         $cart_details[] = array(

         "product_name" => $product_name, 
         "price" => $price, 
         "subtotal" => $subtotal, 
         "pic_name" => $pic_name, 
         "each_item" => $quantity, 
         "subtotal" => $subtotal, 
         "item_id" =>$item_id, 
         "i" => $i 

         ); 

         $i++; 
        } 
       } 

       $stmt->close(); 
      } 



     $response['total'] = $cartTotal; 
     $response['cart'] = $cart_details; 
     echo json_encode($response); 
    } 
+0

啊哈,現在我們正在某處。如果我只在購物車中有兩件商品,這完美地工作。只要我有3並刪除最後一個,一些事情會發生可怕的錯誤,並在控制檯它顯示第二個最後一項與它的總數。 – user8463989

+0

嘗試註釋掉這行'sort($ _ SESSION ['cart_array']);' –

+0

這是sort()函數讓我感到困惑。我刪除了,一切都很好 – user8463989

相關問題