add to cart with AJAX and modal

Published 1 year ago by m.donicova

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

Best Answer (As Selected By m.donicova)
m.donicova

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);
            }
            });
        });
    });
jlrdw
jlrdw
1 year ago (227,770 XP)

See this tutorial to get a general idea: http://phppot.com/php/php-shopping-cart-with-jquery-ajax/

May not be exactly your use case, but will give some ideas.

m.donicova

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

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

Codeskills

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

m.donicova

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', '[email protected]');

PS: skype nepouzivam

m.donicova

whoops another stupid mistake url must be

var url = "/ajaxadd"

but still not added product to cart

Codeskills

What's the error now?

Codeskills

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

m.donicova

Tokenmismatch

m.donicova

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

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

aditya5670

Please sign in or create an account to participate in this conversation.