Shoken's avatar

Using AJAX with Laravel for simple operations

Ok, so my goal is very simple: when the user clicks on the button "Add to Cart", the item gets added to the cart without reloading the page. To do this, I know I have to use AJAX in my Laravel environment.

Here is my HTML button:

<button id="cart" class="btn-round">Add to cart</button> 

This is my script:

<script>
        $("#cart").click(function()
        {
            $.ajax(
                {
                type: "POST",
                url: '/addtocart',
                data: { itemid: 2 },
                }
                )
        });
    </script>

I have added this route to my web:

Route::post('/addtocart', 'CartController@add');

And lastly, this is my Controller:

class CartController extends Controller
{
    //

    public function add($itemid){

        if (Auth::guest())
        {return redirect('/login');}
        else{

            $userid=Auth::user()->id;
            $item=Product::find($itemid);

            $cartitem=new Cart;
            $cartitem->user_id=$userid;
            $cartitem->product_variant_id=$itemid;
            $cartitem->totalprice=$item->normalPrice;

            $cartitem->save();

            return redirect('/products/'.$itemid);


        }
    }
}

As you can see I have hardcoded some values to test stuff, but it does not work. I don't get any errors so I think the Controller is actually never called. The route should be enough, right? Or maybe there are some syntax errors in my AJAX code? I find the online documentation for AJAX extremely confusing.

0 likes
3 replies
click's avatar

Wild guess, you are not passing the CSRF token with your request. This token is required (by default) when you do a POST, PUT or DELETE request. There are quite some examples around on how to pass this token with your ajax request. The official docs is one of them: https://laravel.com/docs/5.7/csrf#csrf-x-csrf-token

Otherwise search on "laravel jquery csrf"

If that still does not work. Figure out what isn't working. Check the debug console of your browser. Look for the error response, the http status code, etc. It should give you enough information to continue the search or ask a question on this forum.

Shoken's avatar

I wanted to give this issue some closure, so people who have the same problem and googled it (hey there!) will find a solution. I read what jlrdw linked and also followed click's advice for CSRF tokens. In the end, I managed to make it work with this code:


 <script>

// "cart" is the ID of my "Add to Cart" button.

                $('#cart').click(function(){
                    $.post("/addtocart",
                        {
//Gets stuff from the form  (e.g.: number of products to add)

                            number: document.getElementById("number").value,
                            itemid: $('#hiddenID').text(),
                        },
                        function() {

//Changes text on the button and disables it, if the function returns success from PHP.

                            document.getElementById("cart").innerHTML = "Added!";
                            document.getElementById("cart").disabled = true;
                    }

                    ) });


            </script>

Please or to participate in this conversation.