Ok, so my goal is very simple: when the user clicks on the button "Add to Cart", the item gets added to the cart without reloading the page. To do this, I know I have to use AJAX in my Laravel environment.
Here is my HTML button:
<button id="cart" class="btn-round">Add to cart</button>
This is my script:
<script>
$("#cart").click(function()
{
$.ajax(
{
type: "POST",
url: '/addtocart',
data: { itemid: 2 },
}
)
});
</script>
I have added this route to my web:
Route::post('/addtocart', 'CartController@add');
And lastly, this is my Controller:
class CartController extends Controller
{
//
public function add($itemid){
if (Auth::guest())
{return redirect('/login');}
else{
$userid=Auth::user()->id;
$item=Product::find($itemid);
$cartitem=new Cart;
$cartitem->user_id=$userid;
$cartitem->product_variant_id=$itemid;
$cartitem->totalprice=$item->normalPrice;
$cartitem->save();
return redirect('/products/'.$itemid);
}
}
}
As you can see I have hardcoded some values to test stuff, but it does not work. I don't get any errors so I think the Controller is actually never called. The route should be enough, right? Or maybe there are some syntax errors in my AJAX code? I find the online documentation for AJAX extremely confusing.