Reputation: 169
I am using jquery and ajax to add stuff to cart and to remove them, so now I have created code remove but after I have click remove its removing but not refreshing the cart. I want this to be done using ajax to refresh the cart. Below is my code for adding, loading and removing from cart
I want this to be done using ajax to refresh the cart. Below is my code for adding, loading and removing from cart
$(document).ready(function() {
load_cart_data();
function load_cart_data() {
$.ajax({
type: "get",
url: "/fetch_cart/cart",
dataType: "json",
cache: false,
success: function(data) {
$("#cart-sidebar").html(data.cart_details);
$(".total_price").text(data.total_price);
$(".total_items").text(data.total_items);
}
});
}
//add to cart
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
var quantity = $('#quantity' + id).val();
$.ajax({
type: "GET",
url: "/add_to_cart/" + id + "/" + quantity,
data: id,
quantity,
cache: false,
success: function(data) {
load_cart_data();
alert(data);
}
});
});
$(document).on('click', '.remove-cart', function() {
var id = $(this).attr('id');
$.ajax({
type: "GET",
url: "/remove_from_cart" + "/" + id,
data: id,
cache: false,
success: function(data) {
load_cart_data();
alert(data);
}
});
});
});
Upvotes: 0
Views: 453
Reputation: 169
public function remove($id)
{
$cart = session()->get('cart');
if (isset($cart[$id])) {
unset($cart[$id]);
session()->put('cart', $cart);
}
session()->flash('success', 'Product removed from cart');
echo 'Product removed from cart';
}
Upvotes: 0
Reputation: 169
public function cart()
{
$total = 0;
$total_items = 0;
$output = '';
if (session('cart')) {
$total_items += count(session('cart', 'id'));
foreach (session('cart') as $id => $details) {
$total += $details['price'] * $details['quantity'];
$output .= '
<li class="item odd">
<a href="#" title="Ipsums Dolors Untra" class="product-image">
<img src="' . $details['photo'] . '" alt="Lorem ipsum dolor" width="65">
</a>
<div class="product-details">
<a href="#" class="remove-cart" id="' . $details['product_id'] . '"> Remove</a>
<p class="product-name">
<a href="#">' . $details['name'] . '</a>
</p>
<strong>' . $details['quantity'] . '</strong> x <span class="price">$' . $details['price'] . '</span>
</div>
</li>
';
}
$data = array(
'cart_details' => $output,
'total_price' => number_format($total, 2),
'total_items' => $total_items,
);
echo json_encode($data);
}
}
//this is my javascript code thats removing data
$(document).on('click', '.remove-cart', function () {
var id = $(this).attr('id');
$.ajax
({
type: "GET",
url: "/remove_from_cart" + "/" + id,
data: id,
cache: false,
success: function (data) {
alert(data);
load_cart_data();
}
});
});
Upvotes: 1