[英]laravel add to cart with ajax
i am trying to add items to my cart with ajax in laravel but i got error 419 (unknown status).我正在尝试使用 Laravel 中的 ajax 将商品添加到我的购物车,但出现错误 419(状态未知)。
here is my ajax code:这是我的ajax代码:
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这是我的 Laravel 控制器功能
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.那么现在我如何在 ajax 成功函数中返回 json 数据。
Add the csrf token to your html head section:将 csrf 令牌添加到您的 html head 部分:
<meta name="csrf-token" content="{{ csrf_token() }}">
After that add this to your js section:之后,将此添加到您的 js 部分:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.