i am trying to add items to my cart with ajax in laravel but i got error 419 (unknown status).
here is my ajax code:
function btnAddCart(param) {
var product_id = param;
var url = "{{ route('cart.add') }}";
$.ajax({
type: "POST",
url: url,
data: { product_id: product_id },
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
};
here is my laravel controller function
public function addToCart(Request $request)
{
$product = Product::findOrFail($request->input('product_id'));
$cart = session()->has('cart') ? session()->get('cart') : [];
if (array_key_exists($product->id, $cart)) {
$cart[$product->id]['quantity']++;
} else {
$cart[$product->id] = [
'title' => $product->title,
'quantity' => 1,
'unit_price' => $product->sale_price,
];
}
session(['cart' => $cart]);
session()->flash('message', $product->title.' added to cart.');
$data = [];
$data['cart'] = session()->has('cart') ? session()->get('cart') : [];
return response()->json($data);
}
so now how do i return json data in ajax success function.
Add the csrf token to your html head section:
<meta name="csrf-token" content="{{ csrf_token() }}">
After that add this to your js section:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.