shahr's avatar
Level 10

How to add to cart in ajax and laravel?

I am trying to add items to my cart with ajax in laraveL.

I am struggling with working on ajax and laravel. I had followed some tutorials on youtube. Please help me! I have been stuck for hours.

Can you suggest an AJAX solution to adding items to the cart without refreshing the page?

blade

<div id="markets">
    <div class="row">
        @foreach($markets as $market)
            <div class="col-lg-3">
                <div class="card">
                    <img src="{{ asset('images/markets/'.$market->image) }}" class="card-img-top">
                    <div class="card-body">
                        <h5 class="card-title">{{ $market->title }}</h5>
                        <p class="card-text">{{ Str::words($market->body, 10) }}</p>
                        <p class="card-text">{{ $market->price }} $</p>
                        <a id="AddToCard_{{ $market->id }}" data-id="{{ $market->id }}" class="card-text add-to-cart cursor-pointer">اضافه</a>
                        <a href="{{ $market->path() }}" class="btn btn-primary">ادامه</a>
                    </div>
                </div>
            </div>
        @endforeach
    </div>
</div>

ajax

<script>
    $(document).ready(function() {
        updateCart();
        {{ $locales = app()->getLocale() }}
        function updateCart(){
            $.get("/{{ $locales }}/carts/", function( data ) {
                    $("#TotalCartItems").text(data.length);
                    $.each( data, function( key, value ) {
                        var Datamsg = "<tr>\n" +
                            "<td>"+ value.id +"</td>\n" +
                            "<td>\n" +
                            "<div class=0form-row justify-content-center\">\n" +
                            "<div class=\"form-group mb-0\">\n" +
                            "<div class=\"input-group mx-auto mb-0\">\n" +
                            "<div class=\"number-input amount\">\n" +
                            "<button onclick=\"this.parentNode.querySelector('input[type=number]').stepDown()\" id=\"decrease\"></button>\n" +
                            "<input class=\"quantity bg-light\" id=\"quantity\" min=\"0\" placeholder=\"0\" name=\"quantity\" value=\""+value.id+"\" type=\"number\">\n" +
                            "<button onclick=\"this.parentNode.querySelector('input[type=number]').stepUp()\" class=\"plus\" id=\"increment\"></button>\n" +
                            "</div>\n" +
                            "</div>\n" +
                            "</div>\n" +
                            "</div>\n" +
                            "</td>\n" +
                            "<td class=\"price\">"+ value.id +"</td>\n" +
                            "<td class=\"total\">0</td>\n" +
                            "</tr>";
                        $("#cartItems").append(Datamsg);
                    });
                }
            );
        }
        $('[id^="AddToCard_"]').click(function() {
            alert('salam');
            var product_id = $(this).attr('data-id');
            $.post("/{{ $locales }}/cart/"+product_id, {
                product_id: product_id,
                count: 1,
            }, function( data ) {
                if(data.result == true){
                    updateCart()
                    $("#cart").slideDown();
                } else if(data.error_code == "not_login"){
                    swal(data.title_message, data.message, "error");
                }
            });
        });
    });
</script>

Note: I do not receive any errors.

0 likes
6 replies
shahr's avatar
Level 10

@nimrod

Yes, I heard. I am currently using Laravel 7. But after completing the project, I will learn a new course from laravel 8 livewire.

yogigurjar's avatar

Assuming you have a button to add products to the cart with a specific product ID, you can attach a click event handler to it and send an AJAX request to the server.

Add to cart

$(document).ready(function(){
    $(".add-to-cart").click(function(){
        var productId = $(this).data("product-id");
        $.ajax({
            url: '/cart/add',
            method: 'POST',
            data: { productId: productId },
            success: function(response){
                console.log(response);
                // Update cart interface or display success message
            },
            error: function(xhr, status, error){
                console.error(xhr.responseText);
                // Handle error response
            }
        });
    });
});

Please or to participate in this conversation.