How to make a shopping cart in Javascript?

Hi There!

In this post, We will explore how to implement a cart object with Javascript and jQuery. Maybe, this is one of the most important object on the web, because all e-commerce sites use the cart for mantain the list of articles that the customer want to buy.
Think for a while about how many money are handled by this object. :astonished:

As a developer, you must know how the cart work and how to write code to have a working class to drive in order to handle some basic function like addProductInCart, removeProductFromCart, getCartValue and finally getItemNum.

Why we need to know how to implement a shopping cart?

We think that this question is the core of our article. If you need to set up an e-commerce website or a MarketPlace for a Customer, you could use one of the CMS that exists on the web: Magento, OsCommerce, Woocommerce, and others work fine! But, this CMS limit your creativity to their programmers’ choices.

What will happen if your customer wants a ** non-standard** e-commerce system? :disappointed:

Can the CMS cover all the strange requests of the customer?

Sometimes the answer is… NO!:point_up:

Then, sometime you must start from scratch!

Basic Requirements

The primary goal of a cart is to store a list of items that the customer could buy. Then, we can imagine the cart object like a list of unique objects, each of them identified by unique id.

For each item, the customer chooses how many want to buy, then each item identified by unique id ** has a quantity property** in which is stored the quantity of product to buy. Also, each item has its own price.

We can write a list of the requirements related to our cart:

  1. Must provide a method to add, update, and remove the item.

  2. Must store the item list across the session; if the user closes the browser, when he returns to the website, the cart should be there!

  3. Must provide a method to be used to calculate the total amount and item number.

Coding the shopping cart in JS :nerd_face:

We start from requirement #2. We need to store the cart in the browser memory avoiding all the problems that in the past we had with SESSION scope variables.

We can use the localStorage feature! We will maintain a copy of the cart object in the localStorage object in order to have all the data locally and not on the server-side! But, in which manner we can implement this?

We just need two simple functions that we named getLocalData and setLocalData.

function getLocalData(name)
{
	return localStorage.getItem(name)
}

function setLocalData(name,value)
{
	if (value!=null)
		localStorage.setItem(name,value);
	else
		localStorage.removeItem(name);
}

Fine! Now we can store and read from the browser memory. Obviously, take into account that a page can access only the data that it has stored.

You are not able to read localStorage of other pages!

Coding the cart object

Now, we need to implement the points #1 and #2.

First, we need a space in which we can save the item.

For simplicity, we’ll be using a Javascript Array.

But, in which manner can we store an array in the localStorage if the localStorage accepts only strings?

The answer is JSON!

Javascript has native support for marshaling and unmarshalling for JSON format, so if we use Javascript we can save all the cart objects without any problem (yes the image can be converted from binary to base64 that is string format).

Initializing the shopping cart

We will start by declaring the variables, one for the array and one for the array item counter and one function that must be called every time a new page that uses the shopping cart is loaded.

var cartObj = null; // global pointer to cart
var cartCI = -1;

function cart_initCart() 
{
	cartObj = new Array();
	cartCI = 0;
	// Check in browser memory if there are a saved cart
	if (getLocalData("NETSELL5_USERCART")!=null)
	{
    // if previoys cart is present load it
		cartCI = getLocalData("NETSELL5_USERCART_CI");
		cartObj = JSON.parse(getLocalData("NETSELL5_USERCART"));
		console.log(cartObj);
	}
	else
	{
		console.log("\t[CART-v2] Cart is empty!");
	}
}

Fantastic! We have a space in which we can add, update, and remove items! Now we need a method to do these actions.

:raised_hand::raised_hand:Be careful here!:raised_hand::raised_hand::fire:
Cart_initCart() must be called when the webpage is ready* because we need to restore the shopping cart from memory!

This action is critical because Javascript would lose variables if the current page changes!

You can do this by attaching a function handler to the body.ready event!

$(window).ready (function () { 
    cart_initCart (); 
});

Adding new items to the shopping cart implementation

The following function handles the insertion of a new item into the shopping cart.

Please note that you are free to store other data and not only the parameters that we use for this article.

function addItemInCart(code,abfor,rifaf,dsart,qtord,prntve,vatval)
{
    // qtord is quantity to order
    // code is the sku or other code
   //abfor is the brand
   // rifaf is the brand code
   // prntve is the unitary price
   //vatval is the percentage fee 

  // if qtord is not numeric method fail
	if (!($.isNumeric(qtord)))
	{
		 return false; 
	}
    	qtord = parseFloat(qtord);
	if (!(qtord > 0)) {
	    alert('insert positive value');
	    return -1;
	}
	
	// make new row
	var newRow = new Object();
	newRow["CDART"] = code;
	newRow["ABFOR"] = abfor;
	newRow["RIFAF"] = rifaf;
	newRow["DSART"] = dsart;

	newRow["QTORD"] = qtord;
	newRow["QTMNV"] = qtmnv;
	newRow["PRNTVE"] = prntve;
	newRow["ALIVA"] = VatVAL;

   // add new item to cart
	cartObj[cartCI++] = newRow;
   
   //save cart in localStorage
setlocalData("NETSELL5_USERCART",JSON.stringify(cartObj));
	setLocalData("NETSELL5_USERCART_CI",cartCI);
	

}

Getting the number of items present in the shopping cart

This function explains itself :laughing:

function cart_getItemsNum_v2() {
	
	var itemInCart = 0;
	for (var xr in cartObj)
	{
	     // i need index of element in this routine so i didn't used OF in iteration
   	    r = cartObj[xr];
	    if (r==null) continue; // Removed ROW - ignore it
	    itemInCart++;
	}
	return itemInCart;
}

Getting the cart value (with and without VAT)

This function computes the total amount of the cart with and without VAT charges.

function cart_getValue_v2() {

	var useVAT = true; 
	
	var kvalueVLMERE=0.0; // without vat
	var kvalueVLMERE_I = 0.0; // with vat
	var kvalueALIVA_VAL = 0.0; // vat chargea

	for (var r of cartObj) // iterate all the item
	{
	    if (r==null) continue; // Removed ROW - ignore it

	    var prntve = parseFloat(r["PRNTVE"]);
	    var aliva = parseFloat(r["ALIVA"]);
	    var qtord = parseFloat(r["QTORD"]);

	    var totRowWithVAT = (prntve + ((prntve*aliva)/100))*qtord;
	    var totRowNOVAT = prntve*qtord;
	    var totRowALIVA = ((prntve*aliva)/100)*qtord; 

	    kvalueVLMERE = kvalueVLMERE + totRowNOVAT;
	    kvalueVLMERE_I = kvalueVLMERE_I + totRowWithVAT; 
	    kvalueALIVA_VAL = kvalueALIVA_VAL + totRowALIVA;
	}

	var cartValueObj = new Object();
	cartValueObj["VLMERE"] = kvalueVLMERE;
	cartValueObj["VLMERE_I"] = kvalueVLMERE_I;
	cartValueObj["ALIVA_VAL"] = kvalueALIVA_VAL;

	return cartValueObj;
}

Removing an item from shopping cart implementation

function cart_removeCartRow_v2(rowid)
{
	cartObj[rowid]=null; // sign row as invalid
}

Updating an item in shopping cart implementation

function cart_updateQtordInRow_v2(rowIndex,newQtord)
{
   // like add item this function fail if qtord is not valid
	if (!($.isNumeric(newQtord)))
	{
		
		 return false; 
	}
    	newQtord = parseFloat(newQtord);
	if (!(newQtord > 0)) {
             alert('insert positive value' );
  
	    return -1;
	}
	
  // update cart
	    cartObj[rowIndex]["QTORD"] = newQtord;
     
	 // update memory
	setLocalData("NETSELL5_USERCART",JSON.stringify(cartObj));
	 
}

The shopping cart is ready!

At this point the three requirements are satisfied. You can copy and paste the code into a blank HTML page in order to use your new cart object. Do not forget to add a reference to jQuery! :laughing:

1 Like