How To Add Products To Cart Without Reloading Page In JQuery

admin_img Posted By Bajarangi soft , Posted On 27-01-2021

Using Jquery we can reload cart without refreshing full image .So today we discuss how to reload only div using jquery.

How To Add Products To Cart Without Reloading Page In JQuery

Let starts,
Step 1:Create index.hmtl file and implement below code in it.

<!-- Nav -->
<nav class="navbar navbar-inverse bg-inverse fixed-top bg-faded">
    <div class="row">
        <div class="col">
            <button type="button" class="btn btn-success" data-toggle="modal" data-target="#cart">Cart (<span
                        class="total-count"></span>)
            </button>
            <button class="clear-cart btn btn-danger pull-right">Clear Cart</button>
        </div>
    </div>
</nav>
<br><br><br><br><br>
<!-- Main -->
<div class="container">
    <div class="row">
        <div class="col">
            <div class="card" >
                <img class="card-img-top" src="image/bag1.jpeg" alt="Card image cap">
                <div class="card-block">
                    <h4 class="card-title">Bag 1</h4>
                    <p class="card-text">Price: $150</p>
                    <a href="#" data-name="Orange" data-price="0.5" class="add-to-cart btn btn-primary">Add to cart</a>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card" >
                <img class="card-img-top"
                     src="image/bag2.jpg"
                     alt="Card image cap">
                <div class="card-block">
                    <h4 class="card-title">Bag 2</h4>
                    <p class="card-text">Price: $120</p>
                    <a href="#" data-name="Banana" data-price="1.22" class="add-to-cart btn btn-primary">Add to cart</a>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card" >
                <img class="card-img-top" src="image/bag3.jpg"
                     alt="Card image cap">
                <div class="card-block">
                    <h4 class="card-title">Bag 3</h4>
                    <p class="card-text">Price: $158</p>
                    <a href="#" data-name="Lemon" data-price="5" class="add-to-cart btn btn-primary">Add to cart</a>
                </div>
            </div>
        </div>
    </div>
</div>

Step 2:Now implement jquery to reload div onclick of button index.php.
<script>
    // ************************************************
    // Shopping Cart API
    // ************************************************

    var shoppingCart = (function () {
        // =============================
        // Private methods and propeties
        // =============================
        cart = [];

        // Constructor
        function Item(name, price, count) {
            this.name = name;
            this.price = price;
            this.count = count;
        }

        // Save cart
        function saveCart() {
            sessionStorage.setItem('shoppingCart', JSON.stringify(cart));
        }

        // Load cart
        function loadCart() {
            cart = JSON.parse(sessionStorage.getItem('shoppingCart'));
        }

        if (sessionStorage.getItem("shoppingCart") != null) {
            loadCart();
        }


        // =============================
        // Public methods and propeties
        // =============================
        var obj = {};

        // Add to cart
        obj.addItemToCart = function (name, price, count) {
            for (var item in cart) {
                if (cart[item].name === name) {
                    cart[item].count++;
                    saveCart();
                    return;
                }
            }
            var item = new Item(name, price, count);
            cart.push(item);
            saveCart();
        }



        

        // Clear cart
        obj.clearCart = function () {
            cart = [];
            saveCart();
        }

        // Count cart
        obj.totalCount = function () {
            var totalCount = 0;
            for (var item in cart) {
                totalCount += cart[item].count;
            }
            return totalCount;
        }

        // Total cart
        obj.totalCart = function () {
            var totalCart = 0;
            for (var item in cart) {
                totalCart += cart[item].price * cart[item].count;
            }
            return Number(totalCart.toFixed(2));
        }

        // List cart
        obj.listCart = function () {
            var cartCopy = [];
            for (i in cart) {
                item = cart[i];
                itemCopy = {};
                for (p in item) {
                    itemCopy[p] = item[p];

                }
                itemCopy.total = Number(item.price * item.count).toFixed(2);
                cartCopy.push(itemCopy)
            }
            return cartCopy;
        }
        return obj;
    })();

    $('.add-to-cart').click(function (event) {
        event.preventDefault();
        var name = $(this).data('name');
        var price = Number($(this).data('price'));
        shoppingCart.addItemToCart(name, price, 1);
        displayCart();
    });

    $('.clear-cart').click(function () {
        shoppingCart.clearCart();
        displayCart();
    });


    function displayCart() {
        var cartArray = shoppingCart.listCart();
        var output = "";
        for (var i in cartArray) {
            output += "<tr>"
                + "<td>" + cartArray[i].name + "</td>"
                + "<td>(" + cartArray[i].price + ")</td>"
                + "<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary' data-name=" + cartArray[i].name + ">-</button>"
                + "<input type='number' class='item-count form-control' data-name='" + cartArray[i].name + "' value='" + cartArray[i].count + "'>"
                + "<button class='plus-item btn btn-primary input-group-addon' data-name=" + cartArray[i].name + ">+</button></div></td>"
                + "<td><button class='delete-item btn btn-danger' data-name=" + cartArray[i].name + ">X</button></td>"
                + " = "
                + "<td>" + cartArray[i].total + "</td>"
                + "</tr>";
        }
        $('.show-cart').html(output);
        $('.total-cart').html(shoppingCart.totalCart());
        $('.total-count').html(shoppingCart.totalCount());
    }


    displayCart();

</script>


Complete Code For Adding Products To Cart Without Reloading Page In JQuery.
<html>
<head>
    <title>How To Add Products To Cart Without Reloading Page In JQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
          integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
            integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"
            integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
            integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
            crossorigin="anonymous"></script>
</head>

<style>
    body {
        padding-top: 40px;
    }

    .show-cart li {
        display: flex;
    }

    .card {
        margin-bottom: 20px;
    }

    .card-img-top {
        width: 200px;
        height: 200px;
        align-self: center;
    }
    .btn-danger {
        float: right;
    }
</style>
<body>
<!-- Nav -->
<nav class="navbar navbar-inverse bg-inverse fixed-top bg-faded">
    <div class="row">
        <div class="col">
            <button type="button" class="btn btn-success" data-toggle="modal" data-target="#cart">Cart (<span
                        class="total-count"></span>)
            </button>
            <button class="clear-cart btn btn-danger pull-right">Clear Cart</button>
        </div>
    </div>
</nav>
<br><br><br><br><br>
<!-- Main -->
<div class="container">
    <div class="row">
        <div class="col">
            <div class="card" >
                <img class="card-img-top" src="image/bag1.jpeg" alt="Card image cap">
                <div class="card-block">
                    <h4 class="card-title">Bag 1</h4>
                    <p class="card-text">Price: $150</p>
                    <a href="#" data-name="Orange" data-price="0.5" class="add-to-cart btn btn-primary">Add to cart</a>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card" >
                <img class="card-img-top"
                     src="image/bag2.jpg"
                     alt="Card image cap">
                <div class="card-block">
                    <h4 class="card-title">Bag 2</h4>
                    <p class="card-text">Price: $120</p>
                    <a href="#" data-name="Banana" data-price="1.22" class="add-to-cart btn btn-primary">Add to cart</a>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card" >
                <img class="card-img-top" src="image/bag3.jpg"
                     alt="Card image cap">
                <div class="card-block">
                    <h4 class="card-title">Bag 3</h4>
                    <p class="card-text">Price: $158</p>
                    <a href="#" data-name="Lemon" data-price="5" class="add-to-cart btn btn-primary">Add to cart</a>
                </div>
            </div>
        </div>
    </div>
</div>


</body>
</html>
<script>
    // ************************************************
    // Shopping Cart API
    // ************************************************

    var shoppingCart = (function () {
        // =============================
        // Private methods and propeties
        // =============================
        cart = [];

        // Constructor
        function Item(name, price, count) {
            this.name = name;
            this.price = price;
            this.count = count;
        }

        // Save cart
        function saveCart() {
            sessionStorage.setItem('shoppingCart', JSON.stringify(cart));
        }

        // Load cart
        function loadCart() {
            cart = JSON.parse(sessionStorage.getItem('shoppingCart'));
        }

        if (sessionStorage.getItem("shoppingCart") != null) {
            loadCart();
        }


        // =============================
        // Public methods and propeties
        // =============================
        var obj = {};

        // Add to cart
        obj.addItemToCart = function (name, price, count) {
            for (var item in cart) {
                if (cart[item].name === name) {
                    cart[item].count++;
                    saveCart();
                    return;
                }
            }
            var item = new Item(name, price, count);
            cart.push(item);
            saveCart();
        }





        // Clear cart
        obj.clearCart = function () {
            cart = [];
            saveCart();
        }

        // Count cart
        obj.totalCount = function () {
            var totalCount = 0;
            for (var item in cart) {
                totalCount += cart[item].count;
            }
            return totalCount;
        }

        // Total cart
        obj.totalCart = function () {
            var totalCart = 0;
            for (var item in cart) {
                totalCart += cart[item].price * cart[item].count;
            }
            return Number(totalCart.toFixed(2));
        }

        // List cart
        obj.listCart = function () {
            var cartCopy = [];
            for (i in cart) {
                item = cart[i];
                itemCopy = {};
                for (p in item) {
                    itemCopy[p] = item[p];

                }
                itemCopy.total = Number(item.price * item.count).toFixed(2);
                cartCopy.push(itemCopy)
            }
            return cartCopy;
        }
        return obj;
    })();

    $('.add-to-cart').click(function (event) {
        event.preventDefault();
        var name = $(this).data('name');
        var price = Number($(this).data('price'));
        shoppingCart.addItemToCart(name, price, 1);
        displayCart();
    });

    $('.clear-cart').click(function () {
        shoppingCart.clearCart();
        displayCart();
    });


    function displayCart() {
        var cartArray = shoppingCart.listCart();
        var output = "";
        for (var i in cartArray) {
            output += "<tr>"
                + "<td>" + cartArray[i].name + "</td>"
                + "<td>(" + cartArray[i].price + ")</td>"
                + "<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary' data-name=" + cartArray[i].name + ">-</button>"
                + "<input type='number' class='item-count form-control' data-name='" + cartArray[i].name + "' value='" + cartArray[i].count + "'>"
                + "<button class='plus-item btn btn-primary input-group-addon' data-name=" + cartArray[i].name + ">+</button></div></td>"
                + "<td><button class='delete-item btn btn-danger' data-name=" + cartArray[i].name + ">X</button></td>"
                + " = "
                + "<td>" + cartArray[i].total + "</td>"
                + "</tr>";
        }
        $('.show-cart').html(output);
        $('.total-cart').html(shoppingCart.totalCart());
        $('.total-count').html(shoppingCart.totalCount());
    }


    displayCart();

</script>

Related Post