Add to cart with Ajax without updating page - Laravel

Asked

Viewed 604 times

0

Hello, I’m trying to use Ajax in a form to add products in the cart without updating the page but I’m not getting, if anyone can help me.

I’m wearing Laravel 5.3 joint on this website:

HTML

<form id="form_ideal" action="/cart/add" method="post" name="add_to_cart">
 {!! csrf_field() !!}
<input type="hidden" name="product" value="{{$product->id}}" />
<input type="hidden" name="qty" value="1" />
<span class="compr-games" title="Add to Cart"><button class="btn-add-to-cart"> Buy Now </button></span>
</form>

Script I’m trying to:

<script type="text/javascript">
        $('#form_ideal').on('submit', function(e) {
            e.preventDefault(); 
            $.ajax({
                type: "POST",
                url: '/cart/add',
                data: $(this).serialize(),
                success: function(msg) {
                swal('Test')
                }
            });
        });
    </script>

What happens is that by clicking the add button to the cart it shows the success message but does not update the quantity in the menu, it gets "0", only updates after I give F5 on the page,

I’m sorry if I’ve done something wrong but I’ve just started messing with Laravel, ajax, that sort of thing..

Thank you

1 answer

0

If you update and appear it means you have already implemented this function, then just pass this amount to the client, to update cart with the method html of J-query, example...

in /Cart/add return quantity like this.

$retorno = array('quantidade' => $quantidadeNoCarrinho, 'msg' => 'sucesso!');
echo json_encode($retorno);
exit();

in Success take this amount

success: function(retorno) {
                alert(retorno.msg);
                $('.quantidade').html(retorno.quantidade)
                }
  • Hello Felipe, this first code I put in the controller? and the second in the script? Sorry as I said I started a little while ago and I don’t understand much yet, Thank you

  • The first is in php, a simple echo, pointing a json, the second is j-query, note that it is a part of your ready code I only made a few modifications.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.