[英]How to update total quantity with ajax Laravel 8
我有我的購物車,為了添加到購物車,我使用的是 ajax。 它有效,但我不知道如何更新位於 header 的總數量。 沒有用於選擇數量的字段的輸入,我希望在每次按下“添加到購物車”按鈕后將其增加 1(使用 ajax)。 我怎樣才能做到這一點?
購物車控制器:
public function addCart(Request $request, $id){
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : NULL;
$cart = new Cart($oldCart);
$cart->add($product, $product->id);
$request = Session::put('cart', $cart);
Session::flash('add-product', $product->name);
return redirect()->back();
}
自定義購物車 class 包含主要邏輯:
public function add($item, $id){
$storedItem = [
'qty' => 0,
'id' => $item->id,
'prod_url' => $item->url,
'code_cat' => $item->category->code,
'url_cat' => $item->category->url,
'name' => $item->name,
'cost' => $item->price,
'price' => $item->price,
'img' => $item->cardImage->path
];
if($this->items){
if(array_key_exists($id, $this->items)){
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['cost'] = $item->price * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->price;
}
添加到購物車按鈕:
<div class="product-icon-container">
<a href="{{ route('basket-add', [ 'id' => $item->id ]) }}" class="scrollOffset btn btn-success mt-2 mb-1">Add to Cart</a>
<a href="#" class="btn btn-danger mt-2 mb-1">Buy now!</a>
</div>
header 中的總數量:
<span class="prodcount">{{ Session::has('cart') ? Session::get('cart')->totalQty : '0' }}</span><i class="fas fa-shopping-basket"></i><span class="basket-text">Cart</span>
簡單的 ajax 請求:
$(document).ready(function() {
$('.product-icon-container').find('a.scrollOffset').click(function (event){
event.preventDefault();
$.ajax({
url: $(this).attr('href')
});
return false;
});
});
在您的add()
方法中,您需要返回更新數量的結果。
public function add($item, $id){
// your code
return response()->json(['success' => true]);
}
然后在您的 ajax 請求中,它有一個success
的 function 來檢查請求是否成功。
$.ajax({
url: $(this).attr('href'),
success: function (data, status, xhr) {
// onReponseSuccess
$('.prodcount').text(your_qty)
},
error: (jqXhr, textStatus, errorMessage) {
// handle onReponseError
}
});
我的問題完全由鏈接上講俄語的 StackOverflow 的用戶解決。
作為一種選擇,您可以通過稍微更改@HEL Mab 的代碼來獲得一個好的解決方案。
$(document).ready(function() {
$('.product-icon-container').find('a.scrollOffset').click(function (event){
event.preventDefault();
let totalQty = parseInt($('.prodcount').text());
$.ajax({
url: $(this).attr('href'),
success: function (data, status, xhr) {
// onReponseSuccess
totalQty++;
$('.prodcount').text(totalQty);
},
error: function(jqXhr, textStatus, errorMessage) {
// handle onReponseError
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.