简体   繁体   English

html表单未向控制程序发送ajax请求

[英]html form not sending ajax request to controler

I am trying to use ajax on add to cart form. 我正在尝试在添加到购物车表格上使用ajax。 but it seems that html form not sending any ajax request. 但似乎html表单未发送任何ajax请求。 When I click on the Add to cart button. 当我单击添加到购物车按钮时。 it show a black page, because i use that ajax check method on controller. 它显示一个黑页,因为我在控制器上使用了该ajax检查方法。

Controller 控制者

 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 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 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>

where did i mistake? 我在哪里弄错了?

if you forget to sent the csrf_token you can solve it as the following: 如果您忘记发送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>");
      }
 });
});

or you can serilize the form: 或者,您可以将表格序列化:

    $('document').on('click','#submitBtn',function(){
   e.preventDefault();
 $.ajax({
      type: "POST",
      url: host + '/addToCart',
      data:$('#add').serialize(),
      success: function( msg ) {
           $("#xx").append("<div>"+msg+"</div>");
      }
 });
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM