Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

m.donicova's avatar

add to cart with AJAX and modal

Hi all I have a simple shop in Laravel where i have for add the product to cart this

<div class="buy">
        <form method="POST" action="{{ URL::to('addcart') }}" class="form-inline" role="form">
            {{ csrf_field() }}
            <input type="hidden" name="product_id" value="{{ $product->id }}">
            <button type="submit"  class="btn btn-primary">Koupit</button>
          </form>
</div>

and for addcart I have

public function postAdd(Request $request) {
        $id = $request->input('product_id');
        $session = $request->session();
        $cartData = ($session->get('cart')) ? $session->get('cart') : array();
        if (array_key_exists($id, $cartData)) {
            $cartData[$id]['qty']++;
        } else {
            $cartData[$id] = array(
                'qty' => 1
            );
        }
        $request->session()->put('cart', $cartData);
        return redirect()->back()->with('message', 'Product Added Successfully!');
    }

now I want for click on submit button show the modal with the information that the product was added to cart a in the same modal to display the actual cart and dispaly two button one for continue in shopping and another for checkout.

I think this must bu some ajax call but in dont know where to start. Is there any example how to solve this? For design I am using the bootstrap and the full code I have on github https://github.com/mardon/MaMushashop

0 likes
13 replies
m.donicova's avatar

I something try but It seems to be wrong

in view I have

<a href="#" id="add" class="btn btn-primary" data-id="{{ $product->id }}">Koupit</a>

and the script

    $(document).ready(function() {

        var product_id = $(this).data('id');
        var url = "/ajaxadd/";
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({

            type: "POST",
            url: url,
            data: { id: product_id },
            success: function (data) {
            console.log(data);

            },
            error: function (data) {
            console.log('Error:', data);
            }
        });
    });

and in the controller I have

    public function ajaxAdd(Request $request) {
        $id = $request->input('product_id');
        $session = $request->session();
        $cartData = ($session->get('cart')) ? $session->get('cart') : array();
        if (array_key_exists($id, $cartData)) {
            $cartData[$id]['qty']++;
        } else {
            $cartData[$id] = array(
                'qty' => 1
            );
        }
        $request->session()->put('cart', $cartData);
        //return redirect()->back()->with('message', 'Product Added Successfully!');
        return response()->json(['msg' => $id], 200);
    }

but this is not function

Codeskills's avatar

@m.donicova I dont see this

var product_id = $(this).data('id');

bind to the click on the button.

It should be something like:

$(document).on('click', '#add', function() {
    var product_id = $(this).data('id');

$.ajax({

            type: "POST",
            url: url,
            data: { id: product_id },
            success: function (data) {
            console.log(data);

            },
            error: function (data) {
            console.log('Error:', data);
            }
        });
}

the backend seems ok.

1 like
Codeskills's avatar

I can also help you out on skype (jiri.zizka @ funfirst . cz)

m.donicova's avatar

of course I edit in many times and I one of the edit i must remove on click function now I have this

    $(document).ready(function() {

        $('a#add').click( function() {
            var product_id = $(this).data('id');
            var url = "/ajaxadd/";

            $.ajaxSetup({
                headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({

            type: "POST",
            url: url,
            data: { id: product_id },
            success: function (data) {
            console.log(data);

            },
            error: function (data) {
            console.log('Error:', data);
            }
            });
        });
    });

in this time I have the

MethodNotAllowedHttpException in RouteCollection.php line 218: error in routes I have

Route::post('/ajaxadd', 'CartController@ajaxAdd');

PS: skype nepouzivam

m.donicova's avatar

whoops another stupid mistake url must be

var url = "/ajaxadd"

but still not added product to cart

Codeskills's avatar

What I can see is that you are sending

data : { id: product_id }

but you are trying to get

$id = $request->input('product_id');

While the "product_id" is not there its only "id".

1 like
m.donicova's avatar
m.donicova
OP
Best Answer
Level 4

ajaxSetup must be set for JQuery

$(document).ready(function() {
        $.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
        });

        $('a#add').click( function() {
            var product_id = $(this).data('id');
            var url = "/ajaxadd";



            $.ajax({

            type: "POST",
            url: url,
            data: { product_id: product_id },
            success: function (data) {
            console.log(data);

            },
            error: function (data) {
            console.log('Error:', data);
            }
            });
        });
    });
m.donicova's avatar

Now I have another problem I have in master layout in navigation this code for number of products in cart

<a href="{{ URL::to('cart') }}"><i class="glyphicon glyphicon-shopping-cart"></i> Košík <span class="badge">{{ $cart_qty }}</span></a>

for $cart_gty i use view composer

        View::composer('layouts.master', function($view) {
            $cart_qty =  Session::get('cart') ? array_sum(array_column(Session::get('cart'), 'qty')) : 0;
            $view->with('cart_qty',$cart_qty);
        });

how I update this wehn i add product to cart with ajax (before I added wih controller and reload the page). Must I reload by jQuery.

I try find the better solution

yogigurjar's avatar

As I was see on tutsmake.com/laravel-shopping-add-item-to-cart-tutorial

Here is an example of how you can make an AJAX request to add a product to the cart in Laravel:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $('.add-to-cart').on('click', function() {
            var productId = $(this).data('product-id');
            
            $.ajax({
                type: 'POST',
                url: '{{ route("cart.add") }}',
                data: {
                    '_token': '{{ csrf_token() }}',
                    'product_id': productId
                },
                success: function(data) {
                    alert(data.message); // Show success message
                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText); // Log any errors to the console
                }
            });
        });
    });
</script>

Here's the controller code for handling the AJAX request to add a product to the cart:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class CartController extends Controller
{
    public function addToCart(Request $request)
    {
        $productId = $request->input('product_id');
        $product = Product::findOrFail($productId);

        // Access or create the cart session
        $cart = session()->get('cart');

        // If the cart is empty, create a new one
        if (!$cart) {
            $cart = [
                $product->id => [
                    'name' => $product->name,
                    'quantity' => 1,
                    'price' => $product->price,
                ]
            ];

            session()->put('cart', $cart);

            return response()->json(['message' => 'Product added to cart successfully']);
        }

        // If the product already exists in the cart, increase its quantity
        if (isset($cart[$product->id])) {
            $cart[$product->id]['quantity']++;
            session()->put('cart', $cart);

            return response()->json(['message' => 'Product added to cart successfully']);
        }

        // If the product is not in the cart, add it
        $cart[$product->id] = [
            'name' => $product->name,
            'quantity' => 1,
            'price' => $product->price,
        ];

        session()->put('cart', $cart);

        return response()->json(['message' => 'Product added to cart successfully']);
    }
}

Please or to participate in this conversation.