我正在尝试在添加到购物车表格上使用ajax。但似乎html表单未发送任何ajax请求。 当我单击添加到购物车按钮时。它显示一个黑页,因为我在控制器上使用了该ajax检查方法。
控制器
public function addToCart(Request $request){
$product = Product::find($request->product_id);
Cart::add($product->id, $product->title, 1, $product->price);
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
if($request->ajax())
return \Response::json($response);
}
JavaScript-AJAX
$('#add').on('submit', function (e) {
e.preventDefault();
var pid = $('#product_id').val();
var cat = $('#category_id').val();
$.ajax({
type: "POST",
url: host + '/addToCart',
data: {product_id: pid, category_id: cat},
success: function( msg ) {
$("#xx").append("<div>"+msg+"</div>");
}
});
});
HTML表格
<form id="add" action="{{ route('addToCart') }}" method="POST">
{{csrf_field()}}
<input type="hidden" id="category_id" name="category_id" value="{{ $px->category_id }}">
<input type="hidden" id="product_id" name="product_id" value="{{ $px->id }}">
<input type="submit" value="Add to Cart" class="bg-color-input">
</form>
<div id="xx"></div>
我在哪里弄错了?
答案 0 :(得分:0)
如果您忘记发送csrf_token,可以按照以下方法解决:
<form id="add" action="{{ route('addToCart') }}" method="POST">
{{csrf_field()}}
<input type="hidden" id="category_id" name="category_id" value="{{ $px->category_id }}">
<input type="hidden" id="product_id" name="product_id" value="{{ $px->id }}">
<input type="button" id="submitBtn" value="Add to Cart" class="bg-color-input">
</form>
<div id="xx"></div>
$('document').on('click','#submitBtn',function(){
e.preventDefault();
var pid = $('#product_id').val();
var cat = $('#category_id').val();
$.ajax({
type: "POST",
url: host + '/addToCart',
data: {product_id: pid, category_id: cat,'_token','{{csrf_token()}}'},
success: function( msg ) {
$("#xx").append("<div>"+msg+"</div>");
}
});
});
或者您可以序列化表格:
$('document').on('click','#submitBtn',function(){
e.preventDefault();
$.ajax({
type: "POST",
url: host + '/addToCart',
data:$('#add').serialize(),
success: function( msg ) {
$("#xx").append("<div>"+msg+"</div>");
}
});
});