Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
2.6 kB
1
Indexable
<script>
        const isAuthenticated = {{ auth()->check() ? 'true' : 'false' }};
        $(document).ready(function() {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
    
            $('.add-to-cart').on('click', function(e) {
                e.preventDefault();
    
                let productId = $(this).data('product-id');
                let quantity = 1;
    
                if (isAuthenticated) {
                    // For logged-in users, use the addToCart route
                    $.ajax({
                        url: "{{ route('customer.cart.addToCart', ['productId' => '__productId__']) }}".replace('__productId__', productId), 
                        method: "POST",
                        data: {
                            product_id: productId,
                            quantity: quantity,
                        },
                        success: function(response) {
                            $('.cart_qty_cls').text(response.totalQuantity);
                            $('.shopping-cart').html(response.cartContent);
    
                            alert('Product added to cart successfully!');
                            location.reload(); // will remove it later to make ajax request for cart item show from carts table.
                        },
                        error: function(response) {
                            alert('There was an error adding the product to the cart.');
                        }
                    });
                } else {
                    // For guest users, use the session-based add route
                    $.ajax({
                        url: "{{ route('cart.add') }}", 
                        method: "POST",
                        data: {
                            product_id: productId,
                            quantity: quantity,
                        },
                        success: function(response) {
                            $('.cart_qty_cls').text(response.totalQuantity);
                            $('.shopping-cart').html(response.cartContent);
    
                            alert('Product added to cart successfully!');
                        },
                        error: function(response) {
                            alert('There was an error adding the product to the cart.');
                        }
                    });
                }
            });
        });
    </script>
Leave a Comment