Hamish Gibson
Hamish Gibson

Reputation: 256

AJAX function in Laravel not posting form data to controller

I have a form in Laravel where users can buy products. I am trying to achieve this dynamically without a page refresh. I am able to call the AJAX function okay but it is not posting the data to the controller and I need help. Everything in the controller works absolutely fine, the data just isn't sending to it.

Here is the HTML form

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

Here is my AJAX function

$(document).ready(function(){
            $('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(url);
                    }
                });
            }));
        });

Here is the first few lines in the controller

 public function buyProduct($university_code, $product_id){
        $player = Player::where('user_id', Auth::user()->id)->first();
        $product = Product::where('id', $product_id)->first();
        $totalPrice = $product->quantity_available * $product->price; 

Upvotes: 2

Views: 3824

Answers (4)

Claude Kirke
Claude Kirke

Reputation: 105

You don't have a request object passed to your controller, but you have declared that it takes two parameters. In the route, you only specify one parameter ($product->id). Here's what the controller method should look like, from my guess: (edited)

public function buyProduct(Request $request){
        $product_id=$request->id; //could also be $product_id=$request()->id;
    }

Access the Request $request object or request() helper to get to data posted to your controller.

the post url: url: $(this).closest("form").attr('action') already translates to /UoE/buy-product/{{$product->id}}, so there is already the product->id/product_id there.

my suggestion is to change your route to a most post-like route /UoE/buy-product and pass the data (product_id, and the csrf token)

$(document).ready(function(){
            $('form.buy-product-form').on('submit', (function (e) {
                e.preventDefault();
                var product_id = $(this).closest("form").attr("id");

                //doesn't matter which csrf, they're all the same
                var csrf=document.querySelector("input[name='_token']").getAttribute('value'); 

                $.ajax({
                    url: '/UoE/buy-product',
                    type: 'POST',
                    data: {
                        'id': product_id,
                        '_token':csrf //pass CSRF
                    },
                    dataType: 'JSON',
                    success: function () {
                        window.alert(url);
                    }
                });
            }));
        });

Upvotes: 0

dazed-and-confused
dazed-and-confused

Reputation: 1333

I just went through the headache of POSTing via AJAX in Laravel. I had similar code to yours and it wasn't working. Some of the changes I made:

<form> tag had no action.

<form id="contact-form" class="main-form">

<button> tag:

<button class="btn btn-primary submit-button" type="button">Submit</button>

AJAX Call:

$(document).ready(function() 
{
    $(".submit-button").click(function(e){            
        form_data = $("form").serialize()
        $.ajax({
            url: "/contact",
            type: "POST",
            data: form_data,
            success: function(data) 
            {
                if ($.isEmptyObject(data.error))
                {
                    handleSuccess(data.success);
                }
                else
                {
                    handleError(data.error);
                }
            }
        });
    });
});

Upvotes: 1

rits
rits

Reputation: 1544

Your controller action is expecting 2 arguments buyProduct($university_code, $product_id), but in form action you are only passing product ID.

Upvotes: 0

delboy1978uk
delboy1978uk

Reputation: 12365

It looks like you can't submit the form, because your button isn't a submit button.

Upvotes: -1

Related Questions