Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Create JavaScript Shopping Cart with Add to Cart Code

#1
Create JavaScript Shopping Cart with Add to Cart Code

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/05/create-javascript-shopping-cart-with-add-to-cart-code.jpg" width="550" height="416" title="" alt="" /></div><div><div class="modified-on" readability="7.047619047619"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on May 16th, 2022.</div>
<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>
<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>
<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>
<h2>What is sessionStorage?</h2>
<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’s persistence is based on the browser’s session availability.</p>
<h2>How to build a JavaScript shopping cart using sessionStorage?</h2>
<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>
<ul>
<li><em>setItem()</em> – 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>
<li><em>getItem()</em> – Read and display the cart items by iterating the sessionStorage object array.</li>
<li><em>removeItem() </em>– Remove a single item from the cart by specifying the item index.</li>
<li><em>clear()</em> – Empty the cart by <a href="https://phppot.com/php/php-unlink-vs-unset/">unsetting</a> the sessionStorage instance.</li>
</ul>
<h2>Shopping cart – checkout – payment</h2>
<p>This section shows the execution flow of the JavaScript shopping cart code. It covers “add to cart” to check out and to the payment step.</p>
<ul>
<li>Step 1: On “add to cart” 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>
<li>Step 2: Then, it gets the buyer’s payment details on a checkout form.</li>
<li>Step 3: Can renders payment options like PayPal with the request parameter array. This array contains purchased items and the buyer’s payment details.</li>
<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>
</ul>
<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>
<h2>JavaScript shopping cart example</h2>
<p>This example provides bare minimal features of a Javascript shopping cart. It supports performing the “<a href="https://phppot.com/php/add-multiple-bulk-product-into-shopping-cart-using-php/">add to cart</a>” and “clear cart” functionalities via JavaScript.</p>
<p>This code also builds and supplies product gallery HTML from JavaScript.</p>
<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>
<h2>HTML code to display shopping cart UI</h2>
<p>This HTML code has placeholders to load UI for the following from JavaScript.</p>
<p>When this document is ready, a JavaScript code prepares HTML for the product grid.</p>
<p>In the product grid, it contains inputs to select a quantity and post to perform the “add to cart” operation.</p>
<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>
<pre class="prettyprint"><code class="language-html">
&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;
</code></pre>
<h2>Client-side code to perform JavaScript shopping cart actions</h2>
<p>This script performs the following.</p>
<ol>
<li>Load product gallery from <a href="https://phppot.com/php/php-json-array-merge/">JSON data</a>.</li>
<li>“Add to cart” action to move a product into the cart table.</li>
<li>Load and change the shopping cart status on each cart action.</li>
<li>Update total cart items and total price on each change.</li>
<li>Empty the cart by <a href="https://phppot.com/php/php-session-time-set-unset/">clearing the session</a>.</li>
</ol>
<h3>Load product gallery from JSON data</h3>
<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>
<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>
<p>In this gallery, each product tile contains the option “add to cart”. It moves the selected product to the cart session by clicking the “Add to cart” button.</p>
<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>
<pre class="prettyprint"><code class="language-javascript">
$(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);
}); 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);
} </code></pre>
<h3>“Add to cart” action to move a product into the cart table</h3>
<p>This “add to cart” JavaScript handler is a core functionality of the example. This code initiates the JavaScript sessionStorage object.</p>
<p>On clicking the “Add to cart” button on the product tile, this function is invoked.</p>
<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 “Add to cart” is placed. For example, it gets the product name, quantity and other details.</p>
<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>
<pre class="prettyprint"><code class="language-javascript">
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 (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();
}
</code></pre>
<h3>Empty the cart by clearing the session</h3>
<p>This JavaScript shopping cart code contains an option to empty the cart table.</p>
<p>It explicitly clears the sessionStorage instance created to have the cart items.</p>
<p>At the end of both “Add to cart” and the “clear cart” 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>
<p>The <code class="language-javascript">showCartTable</code>&nbsp;function is called for updating the cart table UI and the total count.</p>
<pre class="prettyprint"><code class="language-javascript">
function emptyCart() { if (sessionStorage.getItem('shopping-cart')) { // Clear JavaScript sessionStorage by index sessionStorage.removeItem('shopping-cart'); showCartTable(); }
}
</code></pre>
<h3>Load cart row, item count, the total amount from sessionStorage object</h3>
<p>This code displays the logic of <code class="language-javascript">showCartTable()</code> to rebuild cart HTML and update UI.</p>
<p>It initiates variables to hold the following data. These are used in the JavaScript shopping cart code.</p>
<ul>
<li>Cart table HTML.</li>
<li>A total number of items added to the cart.</li>
<li>A total amount of the purchased cart items.</li>
</ul>
<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>
<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>
<pre class="prettyprint"><code class="language-javascript">
function 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));
}
</code></pre>
<h2>JavaScript shopping cart output screenshot</h2>
<p>The output will be familiar to whom already have seen my older shopping cart code created in PHP.</p>
<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>
<p><img 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/20...00x227.jpg 300w, https://phppot.com/wp-content/uploads/20...68x581.jpg 768w, https://phppot.com/wp-content/uploads/20...output.jpg 800w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>Persistent JavaScript shopping cart with localStorage instance</h2>
<p>The WebStorage API’s sessionStorage will be expired when the browser is closed. This API provides one more storage object which is localStorage.</p>
<p>The localStorage object is similar to sessionStorage. The only difference is that the localStorage keeps data until explicit action.</p>
<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’ cart items even if they closed the browser.</p>
<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>
<p class="code-heading">cart-local-storage.js</p>
<pre class="prettyprint"><code class="language-javascript">
$(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();
}); 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();
} function emptyCart() { if (localStorage.getItem('shopping-cart')) { // Clear JavaScript localStorage by index localStorage.removeItem('shopping-cart'); showCartTable(); }
} function removeCartItem(index) { if (localStorage.getItem('shopping-cart')) { var shoppingCart = JSON.parse(localStorage.getItem('shopping-cart')); localStorage.removeItem(shoppingCart[index]); showCartTable(); }
} 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));
} 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);
} </code></pre>
<h2>Security caution</h2>
<p>Until the “add to cart” step, the client-side handling is fine. When proceeding with checkout, it is preferable to use server-side middleware.</p>
<p>It is for safety purposes to handle security loopholes. It will do the sanitization, validation of data authenticity and more verification process.</p>
<h2>Conclusion</h2>
<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>
<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>
<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>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/javascript-shopping-cart/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/05/...cart-code/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016