Answer the question
In order to leave comments, you need to log in
How to display qty data from ajax session without reloading the page?
I am writing an online store in yii2.
It remains to make sure that when adding, the quantity of goods next to the cart icon changes.
The goods themselves are added by Ajax. With this order.
The cart icon is in view, fixed to the right.
I added to the view
$session = Yii::$app->session;
$session->open();
<div class="fix_cart" onclick="return getCart()"id="fix_cart">
<li class="header-cart dropdown default-dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
<div class="header-btns-icon">
<i class="fa fa-shopping-cart"></i>
<span class="qty"><?=$_SESSION['cart.qty']?></span>
</div>
</a>
</li>
</div>
class Cart extends ActiveRecord
{
public function addToCart($product, $qty = 1){
if (isset($_SESSION['cart'][$product->id])){
$_SESSION['cart'][$product->id]['qty'] += $qty;
}else{
$_SESSION['cart'][$product->id] = [
'qty' => $qty,
'name' => $product->title,
'url' => $product->chpu,
'price' => $product->price,
'img' => $product->images->filePath
];
}
$_SESSION['cart.qty'] = isset($_SESSION['cart.qty']) ? $_SESSION['cart.qty'] + $qty : $qty;
$_SESSION['cart.sum'] = isset($_SESSION['cart.sum']) ? $_SESSION['cart.sum'] + $qty * $product->price : $qty * $product->price;
}
public function recalc($id){
if(!isset($_SESSION['cart'][$id])) return false;
$qtyMinus = $_SESSION['cart'][$id]['qty'];
$sumMinus = $_SESSION['cart'][$id]['qty'] * $_SESSION['cart'][$id]['price'];
$_SESSION['cart.qty'] -= $qtyMinus;
$_SESSION['cart.sum'] -= $sumMinus;
unset($_SESSION['cart'][$id]);
}
}
$('.add-to-cart').on('click', function(e){
e.preventDefault();
var id = $(this).data('id'),
qty = $('#qty').val();
$.ajax({
url: '/cart/add',
data: {id: id, qty: qty},
type: 'GET',
success: function(res) {
// showCart(res);
},
error: function () {
alert('Error');
}
});
});
showCart(res);
<span class="qty"><?=$_SESSION['cart.qty']?></span>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question