my fellow problem solvers. Hopefully, you have a productive day. I am working on an e-commerce website project whereby I do it by using Laravel 8. So far I have reached a point to create ‘add to cart’ so as customers could do shopping. By reading different tutorials I am grateful that I can add products to the cart, edit and update them also deleting. But I want it to work without refreshing the page. I used Jquery to create Ajax requests as a lot of tutorials suggested. I think it will be simple for you to understand and help if I will show my codes.
here is my ‘add to cart’ link
<li class="add_to_cart"><a href="javascript:void(0)" data-tippy="Add to cart" onclick="addtocart(<?php echo $product->productID ?>)" data-tippy-placement="top" data-tippy-arrow="true" data-tippy-inertia="true"> <span class="lnr lnr-cart"></span></a></li>
Here is Ajax and Jquery
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function quickview(id) {
$.get('/quickview/'+id, function (response) {
if (response) {
$("#id").html(response.id);
$("#brand").html(response.brand);
$("#productname").html(response.product_name);
$("#price").html(response.price);
$("#description").html(response.product_context);
$("#img").attr('src',response.image);
}
})
}
function addtocart(id) {
var _url = '/product/add-to-cart/'+id;
$.ajax({
url: _url,
method: "GET",
data: {
_token: '{{ csrf_token() }}',
id: id
},
success: function (response) {
window.location.reload();
// I think here is where I stuck,
},
error: function (data) {
console.log('Error:', data);
}
});
}
</script>
Here is my route
Route::get('/product/add-to-cart/{id}', [ProductController::class, 'addToCart'])->name('add.to.cart')->middleware('loggedin');
Here is controller
public function addToCart($id)
{
$product = Product::findOrFail($id);
$cart = session()->get('cart', []);
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
} else {
$cart[$id] = [
"name" => $product->product_name,
"quantity" => 1,
"price" => $product->price,
"maelezo" => $product->product_context,
"image" => $product->image
];
}
session()->put('cart', $cart);
return response()->json(['success' => true]);
// return response()->json($cart);
//return response()->json($cart);
}
2
Answers
The simplest solution for this would be removing
href
attribute fromanchor
tag.Other solution would be changing anchor tag with buttons or, a simple span {custom designed button}.
Adding button inside form or
input type='submit'
will submit the form so be aware of that.How it works
Answering in accordance with your comment on my previous answer.
Working example here
Sample HTML
Script
For any queries comment down.