简体   繁体   中英

Laravel ajax form data not posting to controller

I finally got my AJAX function working and it correctly posted data to the controller. But it only worked when the data being sent was included in the form action- /UoE/buy-product/{{product_id}}. But I only want the form action to be /UoE/buy-product/, as otherwise I am essentially sending the data twice. Once here, and once in my ajax function.

Here is my view

<form class="buy-product-form" id="{{$product->id}}" action="{{url('/UoE/buy-product')}}" method="POST">
                                    {{csrf_field()}}
                                    <button class="pull-right btn btn-primary">BUY NOW</button>
                                </form>

Here is my AJAX function

$(document).ready(function(){
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $('form.buy-product-form').on('submit', (function (e) {
                e.preventDefault();
                var product_id = $(this).closest("form").attr("id");
                $.ajax({
                    url: $(this).closest("form").attr('action'),
                    type: 'POST',
                    data: {'id': product_id},
                    dataType: 'JSON',
                    success: function () {
                        window.alert($(this).closest("form").attr('action'));
                    }
                });
            }));
        });

Here is the first line of my controller (everything else here works fine)

 public function buyProduct(Request $request){
        $product_id = $request->id;

And here is my routes.php file

Route::post('/{university_code}/buy-product', 'UserController@buyProduct');

设法修复它,我更改了路由文件并在单击按钮时将其删除。

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.

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