Reputation: 336
I have cart functionality in my project where IDs of the items are stored in a js array object and the length of the array object is shown in cart. I want to load a view and display the cart items there in the view therefore I want to send the js array object as a parameter to laravel controller function through <a>
tag when the user clicks on it.
Here is the <a>
tag which should send the cart
object to laravel controller:
<a href="#" >
<i class="fa fa-shopping-cart"></i>
<span id="cartLength"></span>
</a>
Here is the js
function that increments cart
array object:
function addToCart(id)
{
if(! cart.includes(id) ) cart.push(id);
cartLength.html(cart.length);
$('#successCart'+id).html('Book added to cart.');
}
Here is the <a>
tag that adds the item to cart by calling addToCart
js function:
<a href="#" class="add-to-cart"
onclick="event.preventDefault(); addToCart('{{$book->id}}');">
Add To Cart
</a>
Here is the controller function that returns view:
public function showCart(Request $request)
{
return view('cart', ['cart' => $request->cart ]);
}
I don't know how to send the cart
js object to laravel controller function through <a>
tag and then load the view from there. Any help is appreciated in advance.
Upvotes: 0
Views: 344
Reputation: 11
If you use an ajax request, on the success of the ajax, collect the (cart items)data and store it in a localstorage. Then display the items onload of the view you want using js. For example:
//let cart be the array you collected
let cart = [];
let formdata = new FormData(cart);
$.ajax({
url:"your/intended/url",
type:"GET",
data: formdata
}).done(function (data){
cartItems = data;
localStorage.setItem('cartItems', data);
location.href = "view/cartPage";
})
Upvotes: 1