Untitled
unknown
plain_text
a year ago
2.6 kB
6
Indexable
<script>
const isAuthenticated = {{ auth()->check() ? 'true' : 'false' }};
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.add-to-cart').on('click', function(e) {
e.preventDefault();
let productId = $(this).data('product-id');
let quantity = 1;
if (isAuthenticated) {
// For logged-in users, use the addToCart route
$.ajax({
url: "{{ route('customer.cart.addToCart', ['productId' => '__productId__']) }}".replace('__productId__', productId),
method: "POST",
data: {
product_id: productId,
quantity: quantity,
},
success: function(response) {
$('.cart_qty_cls').text(response.totalQuantity);
$('.shopping-cart').html(response.cartContent);
alert('Product added to cart successfully!');
location.reload(); // will remove it later to make ajax request for cart item show from carts table.
},
error: function(response) {
alert('There was an error adding the product to the cart.');
}
});
} else {
// For guest users, use the session-based add route
$.ajax({
url: "{{ route('cart.add') }}",
method: "POST",
data: {
product_id: productId,
quantity: quantity,
},
success: function(response) {
$('.cart_qty_cls').text(response.totalQuantity);
$('.shopping-cart').html(response.cartContent);
alert('Product added to cart successfully!');
},
error: function(response) {
alert('There was an error adding the product to the cart.');
}
});
}
});
});
</script>Editor is loading...
Leave a Comment