{"id":124875,"date":"2022-05-16T13:04:15","date_gmt":"2022-05-16T13:04:15","guid":{"rendered":"https:\/\/phppot.com\/?p=16916"},"modified":"2022-05-16T13:04:15","modified_gmt":"2022-05-16T13:04:15","slug":"create-javascript-shopping-cart-with-add-to-cart-code","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/05\/16\/create-javascript-shopping-cart-with-add-to-cart-code\/","title":{"rendered":"Create JavaScript Shopping Cart with Add to Cart Code"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.047619047619\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on May 16th, 2022.<\/div>\n<p>Do you want a shopping cart built entirely in JavaScript? With session \/ storage everything! With no PHP or server-side code, then read on and rock on.<\/p>\n<p>Earlier I have written a lot of PHP shopping cart code using server-side sessions. Now let us see a similar concept on the client-side to build a JavaScript shopping cart.<\/p>\n<p>The <strong>Window.sessionStorage<\/strong> is the right solution to create a session-based shopping cart. It is free from PHP or other server-side code, unlike <a href=\"https:\/\/phppot.com\/php\/simple-php-shopping-cart\/\">previous eCommerce examples<\/a>.<\/p>\n<h2>What is sessionStorage?<\/h2>\n<p>The sessionStorage is one of the <a href=\"https:\/\/www.ecma-international.org\/publications-and-standards\/standards\/ecma-262\/\">standard JavaScript concepts<\/a> of WebStorage API. It is a client-side session object that tends to set, get and clear data with respect to it. This object\u2019s persistence is based on the browser\u2019s session availability.<\/p>\n<h2>How to build a JavaScript shopping cart using sessionStorage?<\/h2>\n<p>The JavaScript shopping cart implementation is possible with sessionStorage like as below. The below table shows the mapping of sessionStorage capability with shopping cart features.<\/p>\n<ul>\n<li><em>setItem()<\/em> \u2013 Add to cart from the shopping gallery by referring to the purchased product id. It also is used to edit a cart item by replacing the value array.<\/li>\n<li><em>getItem()<\/em> \u2013 Read and display the cart items by iterating the sessionStorage object array.<\/li>\n<li><em>removeItem() <\/em>\u2013 Remove a single item from the cart by specifying the item index.<\/li>\n<li><em>clear()<\/em> \u2013 Empty the cart by <a href=\"https:\/\/phppot.com\/php\/php-unlink-vs-unset\/\">unsetting<\/a> the sessionStorage instance.<\/li>\n<\/ul>\n<h2>Shopping cart \u2013 checkout \u2013 payment<\/h2>\n<p>This section shows the execution flow of the JavaScript shopping cart code. It covers \u201cadd to cart\u201d to check out and to the payment step.<\/p>\n<ul>\n<li>Step 1: On \u201cadd to cart\u201d action the sessionStorage object builds the <a href=\"https:\/\/phppot.com\/php\/generate-ecommerce-purchase-invoice-pdf-using-php-script\/\">purchased item<\/a> array.<\/li>\n<li>Step 2: Then, it gets the buyer\u2019s payment details on a checkout form.<\/li>\n<li>Step 3: Can renders payment options like PayPal with the request parameter array. This array contains purchased items and the buyer\u2019s payment details.<\/li>\n<li>Step 4: An alternate to step 3, that is, an email checkout. This suits the shopping cart not dealing with instant payment on the flow.<\/li>\n<\/ul>\n<p>In this tutorial, we will see steps 1 and 2 of a JavaScript shopping cart. You can integrate with the payment options coded with different articles. Example: <a href=\"https:\/\/phppot.com\/php\/how-to-integrate-paypal-checkout-in-ecommerce-website\/\">Integrate PayPal checkout into the eCommerce website<\/a>.<\/p>\n<h2>JavaScript shopping cart example<\/h2>\n<p>This example provides bare minimal features of a Javascript shopping cart. It supports performing the \u201c<a href=\"https:\/\/phppot.com\/php\/add-multiple-bulk-product-into-shopping-cart-using-php\/\">add to cart<\/a>\u201d and \u201cclear cart\u201d functionalities via JavaScript.<\/p>\n<p>This code also builds and supplies product gallery HTML from JavaScript.<\/p>\n<p>It is a <a href=\"https:\/\/phppot.com\/php\/create-ajax-based-event-management-system-with-bootstrap\/\">jQuery-based client-side implementation<\/a> with the use of JavaScript sessionStorage.<\/p>\n<h2>HTML code to display shopping cart UI<\/h2>\n<p>This HTML code has placeholders to load UI for the following from JavaScript.<\/p>\n<p>When this document is ready, a JavaScript code prepares HTML for the product grid.<\/p>\n<p>In the product grid, it contains inputs to select a quantity and post to perform the \u201cadd to cart\u201d operation.<\/p>\n<p>The&nbsp;<em>cart.js<\/em> handles the client-side code to perform the <a href=\"https:\/\/en.wikipedia.org\/wiki\/E-commerce\" target=\"_blank\" rel=\"noopener\">shopping cart operations<\/a>. It will be included in this template.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-html\">\n&lt;div class=\"container\"&gt; &lt;!-- Shopping cart table wrapper --&gt; &lt;div id=\"shopping-cart\"&gt; &lt;div class=\"txt-heading\"&gt; &lt;h1&gt;Shopping cart&lt;\/h1&gt; &lt;\/div&gt; &lt;a onClick=\"emptyCart()\" id=\"btnEmpty\"&gt;Empty Cart&lt;\/a&gt; &lt;table class=\"tbl-cart\" cellpadding=\"10\" cellspacing=\"1\"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Name&lt;\/th&gt; &lt;th class='text-right' width=\"10%\"&gt;Unit Price&lt;\/th&gt; &lt;th class='text-right' width=\"5%\"&gt;Quantity&lt;\/th&gt; &lt;th class='text-right' width=\"10%\"&gt;Sub Total&lt;\/th&gt; &lt;\/tr&gt; &lt;\/thead&gt; &lt;!-- Cart table to load data on \"add to cart\" action --&gt; &lt;tbody id=\"cartTableBody\"&gt; &lt;\/tbody&gt; &lt;tfoot&gt; &lt;tr&gt; &lt;td class=\"text-right\"&gt;Total:&lt;\/td&gt; &lt;td id=\"itemCount\" class=\"text-right\" colspan=\"2\"&gt;&lt;\/td&gt; &lt;td id=\"totalAmount\" class=\"text-right\"&gt;&lt;\/td&gt; &lt;\/tr&gt; &lt;\/tfoot&gt; &lt;\/table&gt; &lt;\/div&gt; &lt;!-- Product gallery shell to load HTML from JavaScript code --&gt; &lt;div id=\"product-grid\"&gt; &lt;div class=\"txt-heading\"&gt; &lt;h1&gt;Products&lt;\/h1&gt; &lt;\/div&gt; &lt;div id=\"product-item-container\"&gt;&lt;\/div&gt; &lt;\/div&gt; &lt;\/div&gt;\n<\/code><\/pre>\n<h2>Client-side code to perform JavaScript shopping cart actions<\/h2>\n<p>This script performs the following.<\/p>\n<ol>\n<li>Load product gallery from <a href=\"https:\/\/phppot.com\/php\/php-json-array-merge\/\">JSON data<\/a>.<\/li>\n<li>\u201cAdd to cart\u201d action to move a product into the cart table.<\/li>\n<li>Load and change the shopping cart status on each cart action.<\/li>\n<li>Update total cart items and total price on each change.<\/li>\n<li>Empty the cart by <a href=\"https:\/\/phppot.com\/php\/php-session-time-set-unset\/\">clearing the session<\/a>.<\/li>\n<\/ol>\n<h3>Load product gallery from JSON data<\/h3>\n<p>The&nbsp;<em><code class=\"language-javascript\">productItem<\/code><\/em> contains the product JSON data. It contains a row of product data with name, price and photo path.<\/p>\n<p>The&nbsp;<em><code class=\"language-javascript\">showProductGallery<\/code><\/em> method iterates this <em><code class=\"language-javascript\">productItem<\/code><\/em> JSON and builds the product gallery HTML.<\/p>\n<p>In this gallery, each product tile contains the option \u201cadd to cart\u201d. It moves the selected product to the cart session by clicking the \u201cAdd to cart\u201d button.<\/p>\n<p>The JavaScript code uses <a href=\"https:\/\/phppot.com\/javascript\/for-each-javascript\/\">for each loop<\/a> to iterate the<em><code class=\"language-javascript\">productItem<\/code><\/em> JSON.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\n$(document).ready(function() { var productItem = [{ productName: \"FinePix Pro2 3D Camera\", price: \"1800.00\", photo: \"camera.jpg\" }, { productName: \"EXP Portable Hard Drive\", price: \"800.00\", photo: \"external-hard-drive.jpg\" }, { productName: \"Luxury Ultra thin Wrist Watch\", price: \"500.00\", photo: \"laptop.jpg\" }, { productName: \"XP 1155 Intel Core Laptop\", price: \"1000.00\", photo: \"watch.jpg\" }]; showProductGallery(productItem);\n}); function showProductGallery(product) { \/\/Iterate javascript shopping cart array var productHTML = \"\"; product.forEach(function(item) { productHTML += '&lt;div class=\"product-item\"&gt;'+ '&lt;img src=\"product-images\/' + item.photo + '\"&gt;'+ '&lt;div class=\"productname\"&gt;' + item.productName + '&lt;\/div&gt;'+ '&lt;div class=\"price\"&gt;$&lt;span&gt;' + item.price + '&lt;\/span&gt;&lt;\/div&gt;'+ '&lt;div class=\"cart-action\"&gt;'+ '&lt;input type=\"text\" class=\"product-quantity\" name=\"quantity\" value=\"1\" size=\"2\" \/&gt;'+ '&lt;input type=\"submit\" value=\"Add to Cart\" class=\"add-to-cart\" onClick=\"addToCart(this)\" \/&gt;'+ '&lt;\/div&gt;'+ '&lt;\/div&gt;'; \"&lt;tr&gt;\"; }); $('#product-item-container').html(productHTML);\n} <\/code><\/pre>\n<h3>\u201cAdd to cart\u201d action to move a product into the cart table<\/h3>\n<p>This \u201cadd to cart\u201d JavaScript handler is a core functionality of the example. This code initiates the JavaScript sessionStorage object.<\/p>\n<p>On clicking the \u201cAdd to cart\u201d button on the product tile, this function is invoked.<\/p>\n<p>It reads the product details from the <a href=\"https:\/\/phppot.com\/jquery\/using-jqgrid-control-with-php\/\">product grid<\/a> where the clicked \u201cAdd to cart\u201d is placed. For example, it gets the product name, quantity and other details.<\/p>\n<p>Using these details, this code prepares the JSON instance of the cart item row. Then, it appends the newly added items to the existing cart sessionStorage object.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\nfunction addToCart(element) { var productParent = $(element).closest('div.product-item'); var price = $(productParent).find('.price span').text(); var productName = $(productParent).find('.productname').text(); var quantity = $(productParent).find('.product-quantity').val(); var cartItem = { productName: productName, price: price, quantity: quantity }; var cartItemJSON = JSON.stringify(cartItem); var cartArray = new Array(); \/\/ If javascript shopping cart session is not empty if (sessionStorage.getItem('shopping-cart')) { cartArray = JSON.parse(sessionStorage.getItem('shopping-cart')); } cartArray.push(cartItemJSON); var cartJSON = JSON.stringify(cartArray); sessionStorage.setItem('shopping-cart', cartJSON); showCartTable();\n}\n<\/code><\/pre>\n<h3>Empty the cart by clearing the session<\/h3>\n<p>This JavaScript shopping cart code contains an option to empty the cart table.<\/p>\n<p>It explicitly clears the sessionStorage instance created to have the cart items.<\/p>\n<p>At the end of both \u201cAdd to cart\u201d and the \u201cclear cart\u201d actions, <a href=\"https:\/\/phppot.com\/php\/ajax-cart-edit-in-php-shopping-cart\/\">the cart table UI is rebuilt with the latest<\/a> session data.<\/p>\n<p>The <code class=\"language-javascript\">showCartTable<\/code>&nbsp;function is called for updating the cart table UI and the total count.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\nfunction emptyCart() { if (sessionStorage.getItem('shopping-cart')) { \/\/ Clear JavaScript sessionStorage by index sessionStorage.removeItem('shopping-cart'); showCartTable(); }\n}\n<\/code><\/pre>\n<h3>Load cart row, item count, the total amount from sessionStorage object<\/h3>\n<p>This code displays the logic of <code class=\"language-javascript\">showCartTable()<\/code> to rebuild cart HTML and update UI.<\/p>\n<p>It initiates variables to hold the following data. These are used in the JavaScript shopping cart code.<\/p>\n<ul>\n<li>Cart table HTML.<\/li>\n<li>A total number of items added to the cart.<\/li>\n<li>A total amount of the purchased cart items.<\/li>\n<\/ul>\n<p>It checks cart sessionStorage and iterates the array if exists. During the iteration, it builds the cart table HTML and computes the total count and price.<\/p>\n<p>The cart sessionStorage data is pushed to the UI via this JavaScript function. It reflects the latest cart state to the end-users.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\nfunction showCartTable() { var cartRowHTML = \"\"; var itemCount = 0; var grandTotal = 0; var price = 0; var quantity = 0; var subTotal = 0; if (sessionStorage.getItem('shopping-cart')) { var shoppingCart = JSON.parse(sessionStorage.getItem('shopping-cart')); itemCount = shoppingCart.length; \/\/Iterate javascript shopping cart array shoppingCart.forEach(function(item) { var cartItem = JSON.parse(item); price = parseFloat(cartItem.price); quantity = parseInt(cartItem.quantity); subTotal = price * quantity cartRowHTML += \"&lt;tr&gt;\" + \"&lt;td&gt;\" + cartItem.productName + \"&lt;\/td&gt;\" + \"&lt;td class='text-right'&gt;$\" + price.toFixed(2) + \"&lt;\/td&gt;\" + \"&lt;td class='text-right'&gt;\" + quantity + \"&lt;\/td&gt;\" + \"&lt;td class='text-right'&gt;$\" + subTotal.toFixed(2) + \"&lt;\/td&gt;\" + \"&lt;\/tr&gt;\"; grandTotal += subTotal; }); } $('#cartTableBody').html(cartRowHTML); $('#itemCount').text(itemCount); $('#totalAmount').text(\"$\" + grandTotal.toFixed(2));\n}\n<\/code><\/pre>\n<h2>JavaScript shopping cart output screenshot<\/h2>\n<p>The output will be familiar to whom already have seen my older shopping cart code created in PHP.<\/p>\n<p>It is designed as a <a href=\"https:\/\/phppot.com\/php\/one-page-checkout-script-free-with-example-template-in-php\/\">single-page shopping cart solution<\/a>. It shows both the gallery and cart on the same page.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-16947\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/05\/javascript-shopping-cart-output-550x416.jpg\" alt=\"javascript shopping cart output\" width=\"550\" height=\"416\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/05\/javascript-shopping-cart-output-550x416.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/05\/javascript-shopping-cart-output-300x227.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/05\/javascript-shopping-cart-output-768x581.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/05\/javascript-shopping-cart-output.jpg 800w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>Persistent JavaScript shopping cart with localStorage instance<\/h2>\n<p>The WebStorage API\u2019s sessionStorage will be expired when the browser is closed. This API provides one more storage object which is localStorage.<\/p>\n<p>The localStorage object is similar to sessionStorage. The only difference is that the localStorage keeps data until explicit action.<\/p>\n<p>So, this concept helps <a href=\"https:\/\/phppot.com\/php\/how-to-build-a-persistent-shopping-cart-in-php\/\">to have a persistent cart<\/a>. That is to retain the customers\u2019 cart items even if they closed the browser.<\/p>\n<p>The source code uses sessionStorage for this JavaScript shopping cart code. Include the following file instead of cart.js if you want to use the localStorage object.<\/p>\n<p class=\"code-heading\">cart-local-storage.js<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\n$(document).ready(function() { var productItem = [{ productName: \"FinePix Pro2 3D Camera\", price: \"1800.00\", photo: \"camera.jpg\" }, { productName: \"EXP Portable Hard Drive\", price: \"800.00\", photo: \"external-hard-drive.jpg\" }, { productName: \"Luxury Ultra thin Wrist Watch\", price: \"500.00\", photo: \"laptop.jpg\" }, { productName: \"XP 1155 Intel Core Laptop\", price: \"1000.00\", photo: \"watch.jpg\" }]; showProductGallery(productItem); showCartTable();\n}); function addToCart(element) { var productParent = $(element).closest('div.product-item'); var price = $(productParent).find('.price span').text(); var productName = $(productParent).find('.productname').text(); var quantity = $(productParent).find('.product-quantity').val(); var cartItem = { productName: productName, price: price, quantity: quantity }; var cartItemJSON = JSON.stringify(cartItem); var cartArray = new Array(); \/\/ If javascript shopping cart session is not empty if (localStorage.getItem('shopping-cart')) { cartArray = JSON.parse(localStorage.getItem('shopping-cart')); } cartArray.push(cartItemJSON); var cartJSON = JSON.stringify(cartArray); localStorage.setItem('shopping-cart', cartJSON); showCartTable();\n} function emptyCart() { if (localStorage.getItem('shopping-cart')) { \/\/ Clear JavaScript localStorage by index localStorage.removeItem('shopping-cart'); showCartTable(); }\n} function removeCartItem(index) { if (localStorage.getItem('shopping-cart')) { var shoppingCart = JSON.parse(localStorage.getItem('shopping-cart')); localStorage.removeItem(shoppingCart[index]); showCartTable(); }\n} function showCartTable() { var cartRowHTML = \"\"; var itemCount = 0; var grandTotal = 0; var price = 0; var quantity = 0; var subTotal = 0; if (localStorage.getItem('shopping-cart')) { var shoppingCart = JSON.parse(localStorage.getItem('shopping-cart')); itemCount = shoppingCart.length; \/\/Iterate javascript shopping cart array shoppingCart.forEach(function(item) { var cartItem = JSON.parse(item); price = parseFloat(cartItem.price); quantity = parseInt(cartItem.quantity); subTotal = price * quantity cartRowHTML += \"&lt;tr&gt;\" + \"&lt;td&gt;\" + cartItem.productName + \"&lt;\/td&gt;\" + \"&lt;td class='text-right'&gt;$\" + price.toFixed(2) + \"&lt;\/td&gt;\" + \"&lt;td class='text-right'&gt;\" + quantity + \"&lt;\/td&gt;\" + \"&lt;td class='text-right'&gt;$\" + subTotal.toFixed(2) + \"&lt;\/td&gt;\" + \"&lt;\/tr&gt;\"; grandTotal += subTotal; }); } $('#cartTableBody').html(cartRowHTML); $('#itemCount').text(itemCount); $('#totalAmount').text(\"$\" + grandTotal.toFixed(2));\n} function showProductGallery(product) { \/\/Iterate javascript shopping cart array var productHTML = \"\"; product.forEach(function(item) { productHTML += '&lt;div class=\"product-item\"&gt;'+ '&lt;img src=\"product-images\/' + item.photo + '\"&gt;'+ '&lt;div class=\"productname\"&gt;' + item.productName + '&lt;\/div&gt;'+ '&lt;div class=\"price\"&gt;$&lt;span&gt;' + item.price + '&lt;\/span&gt;&lt;\/div&gt;'+ '&lt;div class=\"cart-action\"&gt;'+ '&lt;input type=\"text\" class=\"product-quantity\" name=\"quantity\" value=\"1\" size=\"2\" \/&gt;'+ '&lt;input type=\"submit\" value=\"Add to Cart\" class=\"add-to-cart\" onClick=\"addToCart(this)\" \/&gt;'+ '&lt;\/div&gt;'+ '&lt;\/div&gt;'; \"&lt;tr&gt;\"; }); $('#product-item-container').html(productHTML);\n} <\/code><\/pre>\n<h2>Security caution<\/h2>\n<p>Until the \u201cadd to cart\u201d step, the client-side handling is fine. When proceeding with checkout, it is preferable to use server-side middleware.<\/p>\n<p>It is for safety purposes to handle security loopholes. It will do the sanitization, validation of data authenticity and more verification process.<\/p>\n<h2>Conclusion<\/h2>\n<p>So, we have created a JavaScript shopping cart code using the sessionStorage object. And also, we saw one more option to add the cart item persistency with the localStorage object.<\/p>\n<p>The client-side shopping cart implementation is not a complete solution. But, it has the advantages of minimalism. It will suit the thin static cart available online.<\/p>\n<p>It is suitable for the shops having client-side integrations connected with <a href=\"https:\/\/phppot.com\/php\/stripe-one-time-payment-with-prebuilt-hosted-checkout-in-php\/\">hosted services<\/a>.<br \/><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/javascript-shopping-cart.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/javascript\/javascript-shopping-cart\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on May 16th, 2022. Do you want a shopping cart built entirely in JavaScript? With session \/ storage everything! With no PHP or server-side code, then read on and rock on. Earlier I have written a lot of PHP shopping cart code using server-side sessions. Now let us see a similar [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":124876,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-124875","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/124875","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=124875"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/124875\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/124876"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=124875"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=124875"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=124875"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}