Session storage is a new feature introduced by the W3C’s “Web Storage” specification. It’s supported in Internet Explorer 8+, Firefox, Chrome, Safari and Opera Desktop (for a complete list, please consult “Can I Use”). In this series of articles, we’ll cover in depth a practical implementation of session storage by creating a complete e-commerce shopping cart with the sessionStorage object and jQuery.
Bear in mind that, in these articles, I’m not going to propose a new technique to replace existing server-side techniques, but rather just a proof of concept of session storage.
Session Storage: A Quick Reminder
We use sessions to store data and share such data across several pages. Usually, a user would pick a product, and we’d save the product’s name along with the chosen quantity and price.
Then, the user would fill out a form with their personal information, and we’d save it in the current session before the end of the process, which is typically the checkout page and the subsequent redirection to the payment gateway (for example, PayPal).
How are shopping carts built? PHP, for instance, makes frequent use of associative arrays to create the basic structure of a shopping cart. Associative arrays enable PHP Web developers to keep session data structured and organized.
JavaScript sessions work differently. Generally, a session expires when the user closes their browser (but bear in mind that the concept of “closing a browser” is not clear on mobile devices). When a session expires, all data stored in the session storage of a Web browser is removed. There’s no need to explicitly initialize a session because in JavaScript a session takes the form of the global sessionStorage object and is always present. It’s up to us to write data into the current session.
Session data comes in the form of key-value pairs, and the value of each key may contain only strings. To write data, we can use the sessionStorage.setItem( name, value ) method:
In this case, the key named total now contains the value 120 as a string, although we’ve used an integer in our call to the .setItem() method. This value will be available until the session expires, unless we use sessionStorage.removeItem( "total" ) to remove the named key or we call sessionStorage.clear() to entirely remove all keys and values from the session storage.
Note that when a key doesn’t exist in session storage, its value is always null. Then, when we remove a key from session storage and try again to get its value, we’d simply get null.
As you may have guessed, our key now is always available, even as the user navigates the pages of our website. To get its value, we simply write the following:
We can also update its value by using sessionStorage.setItem() again with a new value:
Now, the key named total has a value of 240 with our last update. Why did we call parseInt()? This is a simple technique to convert a numerical string into a true number, ensuring that our calculation will be consistent. Remember that all values in session storage are strings, and our calculations must be between only numbers.
But wait! What about objects? Objects may be stored in session storage by first turning them into JSON strings (with JSON.stringify()) and then back into JavaScript objects (with JSON.parse()):
To update our object, we simply extend it and then repeat the procedure above.
Security Considerations
Security is important. If we read the security notes of the W3C’s specification, then we’d be aware of the security risks of even a client-side technology such as Web storage.
The US Computer Emergency Readiness Team’s technical paper on website security (PDF) clearly states:
“Every community organization, corporation, business, or government agency relies on an outward-facing website to provide information about themselves, announce an event, or sell a product or service. Consequently, public-facing websites are often the most targeted attack vectors for malicious activity.”
Even if a browser session ends when the browser itself is closed, malicious attacks can still take place, especially if the browser has been compromised by certain exploits. Moreover, compromised websites can often be used to spread malware that targets particular browsers.
For this reason, make sure your website is safe before relying on any technique to store data in the browser. Keeping a website safe is beyond the scope of this article, but by simply following security best practices, you should be able to benefit from Web storage without worrying too much about its security implications.
Our Sample Project: Winery
Our sample project is an online store that sells wine. It’s a simple e-commerce website whose only complication is in how its shipping charges are calculated.
In short, wines are sold in packages of six bottles. This means that the total quantity of bottles sold must always be in multiples of six. Shipping charges are calculated, then, according to the total quantity of bottles sold.
Our store will rely on PayPal, so we’ll have to create a Business account in PayPal Sandbox to test our code.
The user may add and remove products from their shopping cart, update the cart, change the quantity of each product, and empty the cart. They have to fill a form with their contact information, specifying whether their billing address is the same as their shipping address.
Before being redirected to PayPal, the user will see a summary page with their personal data, their cart, and the cart’s total price plus shipping charges.
After completing their purchase, the user should be redirected back to our website. This is the only step of the process that we can’t handle only with JavaScript. PayPal will send back various data over an HTTP request that has to be processed with a server-side language (such as PHP). If you need more information to get started with this kind of processing, please consult PayPal’s tutorial.
HTML Structure
Our project is made up of the following sections:
index.html
This contains the list from which users may add products to their shopping cart, specifying the quantity for each product.
cart.html
This is the shopping cart page where users may update or empty their cart. Alternatively, they can go back to the main page to continue shopping or proceed to the checkout page.
checkout.html
On this page, users fill out a form with their personal information — specifically, their billing and shipping addresses.
order.html
This page contains a brief summary of the user’s order plus the PayPal form. Once a user submits the form, they will be redirected to PayPal’s landing page.
We’ll go over the markup for this project in the following sections.
index.html
The main components of this page are the forms that enable the user to add products to their shopping cart.
The data attributes used here for storing product names and prices can be accessed via jQuery using the .data() and $.data() methods.
cart.html
Our shopping cart page is made up of three components: a table with the product’s information, an element that displays the subtotal, and a list
of cart actions.
The table contained in this page is empty, and we’ll fill it with data via JavaScript. The element that displays the subtotal works just as a placeholder for JavaScript. The first two actions, “Update Cart” and “Empty Cart,” will be handled by JavaScript, while the latter two actions are just plain links to the product’s list page and the checkout page, respectively.
checkout.html
This page has four components:
a table that shows the ordered items (the same table shown earlier in the shopping cart section), plus the final price and shipping charges;
a form in which the user must fill in their billing details;
a form with shipping information;
a checkbox to enable the user to specify that their billing details are the same as their shipping details.
Data attributes are used here for validation. The data-type attribute specifies the type of data we’re validating, and data-message contains the error message to be shown in case of failure.
I didn’t use the email validation built into Web browsers just for the sake of simplicity, but you could use it if you want.
order.html
This final page contains a brief recap of the user’s order, their details and the PayPal form.
The PayPal form and other elements of this page are initially empty, except for those fields that don’t need to be generated dynamically.
JavaScript Code
The CSS layout of this project will have no actual influence on the goal we want to achieve. Even if we disabled CSS entirely, the project would continue to function, thanks to the strong relationship between the HTML’s structure and the JavaScript’s behavior.
We’ll use an object-oriented approach because of the complexity of our goals. Our object will be based on a simple constructional pattern and will use both private and public methods.
Object Structure
Our object has a very simple structure. The constructor function both initializes the top-level element that wraps our DOM’s entire structure and invokes the initialization method.
The object’s instance is created when the DOM is ready. We can test that everything has worked fine as follows:
This outputs the following:
Now that we know our object has been instantiated correctly, we can define its properties.
Object Properties
The properties of our object break down into two categories: first, the properties for handling calculations, forms and validation, and secondly, the references to HTML elements.
Let’s go over these properties one by one.
Storage and other properties:
cartPrefix
A prefix to be prepended to the cart’s name key in session storage
cartName
The cart’s name key in session storage (combines the cartPrefix string with the cart string)
shippingRates
The shipping rate key in session storage
total
The total’s key in session storage
storage
Shortcut to the sessionStorage object.
currency
An HTML entity used to display the current currency in the layout
currencyString
The current currency symbol used in the element’s text
paypalCurrency
PayPal’s currency text code
paypalBusinessEmail
The email address of your PayPal Business account
paypalURL
The URL of PayPal’s form (defaults to the URL of PayPal Sandbox)
requiredFields
An object containing the patterns and rules for form validation
References to elements:
$formAddToCart
The forms for adding products to the shopping cart
$formCart
The shopping cart form
$checkoutCart
The checkout’s shopping cart form
$checkoutOrderForm
The checkout’s form where users input their personal information
$shipping
The element that contains and displays shipping rates
$subTotal
The element that contains and displays the total charges
$shoppingCartActions
The elements that contain the actions related to the shopping cart
$updateCartBtn
The button to update the shopping cart
$emptyCartBtn
The button for emptying the cart
$userDetails
The element that contains and displays the information entered by the user
$paypalForm
PayPal’s form
All of the elements are prefixed with the $ sign, meaning that they’re jQuery objects. But not all of these elements are available on all pages. To check whether a jQuery element exists, simply test its length property:
Another approach, not used in our project, is to add a particular ID or class to the body element and perform actions conditionally:
Object Methods
The actions of our code take place in our object’s methods, which, in turn, can be divided into public and private methods. Private methods operate in the background, so to speak, and help the public methods perform their tasks. These methods are prefixed with an underscore and are never used directly.
Public methods, meanwhile, operate directly on page elements and data, and they’re unprefixed. We’ve already seen the init() method, which simply initializes properties and other public methods in the object’s constructor function. The other methods will be explained below.
Private Methods (Helpers)
The first private method, _emptyCart(), simply empties the current session storage in the browser:
To format a number by a set number of decimal places, we implement the _formatNumber() method:
This method makes use of JavaScript’s toFixed() method of the Number object. Its role in our project is to properly format prices.
Because not all of the prices in our pages are contained in data attributes, we need a specialized method to extract the numeric portion of a string from text nodes. This method is named _extractPrice():
Above, self is a reference to the $.Shop object, and we’ll need it every time we want to access a property or a method of our object without worrying much about scope.
You can bulletproof this method by adding a further routine that strips out all trailing white space:
Bear in mind that jQuery’s $.trim() method removes all new lines, spaces (including non-breaking spaces) and tabs from the beginning and end of a string. If these white space characters occur in the middle of a string, they are preserved.
Then, we need two methods to convert strings into numbers and numbers into strings. This is necessary to perform calculations and to display the results on our pages.
Above, _convertString() runs the following tests:
Does the string have a decimal format? If so, it uses the parseFloat() function.
Does the string have an integer format? If so, it uses the parseInt() function.
If the format of the string cannot be detected, it uses the Number() constructor.
If the result is a number (tested with the isNaN() function), it returns the number. Otherwise, it outputs a warning to the JavaScript console and returns false.
By contrast, _convertNumber() simply invokes the toString() method to convert a number into a string.
The next step is to define two methods to convert a JavaScript object into a JSON string and a JSON string back into a JavaScript object:
The first method makes use of the JSON.parse() method, while the latter invokes the JSON.stringify() method (see Mozilla Developer Network’s article on “Using Native JSON”).
Why do we need these methods? Because our cart will also store the information related to each product using the following data format (spaces added for legibility):
Key
Value
winery-cart
{ "items": [ { "product": "Wine #1", "qty": 5, "price": 5 } ] }
The winery-cart key contains a JSON string that represents an array of objects (i.e. items) in which each object shows the relevant information about a product added by the user — namely, the product’s name, the quantity and the price.
It’s pretty obvious that we also now need a specialized method to add items to this particular key in session storage:
This method gets the cart’s key from session storage, converts it to a JavaScript object and adds a new object as a JSON string to the cart’s array. The newly added object has the following format:
Now, our cart key will look like this:
Key
Value
winery-cart
{ "items": [ { "product": "Wine #1", "qty": 5, "price": 5 }, { "product": "Test", "qty": 1, "price": 2 } ] }
Shipping is calculated according to the overall number of products added to the cart, not the quantity of each individual product:
You can replace this method’s routines with your own. In this case, shipping charges are calculated based on specific amounts.
We also need to validate the checkout form where users insert their personal information. The following method takes into account the special visibility toggle by which the user may specify that their billing information is the same as their shipping information.
When validation messages are added upon the form being submitted, we need to clear these messages before going any further. In this case, we take into account only the fields contained in a fieldset element that is still visible after the user has checked the visibility toggle.
Validation takes place by checking whether the current field requires a simple string comparison (data-type="string") or a regular expression test (data-type="expression"). Our tests are based on the requiredFields property. If there’s an error, we’ll show a message by using the data-message attribute of each field.
Note that the validation routines used above have been inserted just for demonstration purposes, and they have several flaws. For better validation, I recommend a dedicated jQuery plugin, such as jQuery Validation.
Last but not least is registering the information that the user has entered in the checkout form:
Again, this method takes into account the visibility of the fields based on the user’s choice. Once the form has been submitted, our session storage may have the following details added to it:
Key
Value
billing-name
John Doe
billing-email
jdoe@localhost
billing-city
New York
billing-address
Street 1
billing-zip
1234
billing-country
USA
Public Methods
Our public methods are invoked in the initialization method (init()). The first thing to do is create the initial keys and values in session storage.
The first check tests whether our values have already been added to session storage. We need this test because we could actually overwrite our values if we run this method every time a document has finished loading.
Now, our session storage looks like this:
Key
Value
winery-cart
{“items”:[]}
winery-shipping-rates
0
winery-total
0
Now, we need to handle the forms where the user may add products to their shopping cart:
Every time a user submits one of these forms, we have to read the product quantity specified by the user and multiply it by the unit price. Then, we need to read the total’s key contained in session storage and update its value accordingly. Having done this, we call the _addToCart() method to store the product’s details in storage. The quantity specified will also be used to calculate the shipping rate by comparing its value to the value already stored.
Suppose that a user chooses the first product, Wine #1, whose price is €5.00, and specifies a quantity of 5. The session storage would look like this once the form has been submitted:
Key
Value
winery-cart
{“items”:[{"product":"Wine #1","price":5,"qty":5}]}
winery-shipping-rates
0
winery-total
25
Suppose the same user goes back to the product list and chooses Wine #2, whose price is €8.00, and specifies a quantity of 2:
Key
Value
winery-cart
{“items”:[{"product":"Wine #1","price":5,"qty":5},{"product":"Wine #2","price":8,"qty":2}]}
winery-shipping-rates
0
winery-total
41
Finally, our eager user returns again to the product list, chooses Wine #3, whose price is €11.00, and specifies a quantity of 6:
Key
Value
winery-cart
{“items”:[{"product":"Wine #1","price":5,"qty":5},{"product":"Wine #2","price":8,"qty":2},{"product":"Wine #3","price":11,"qty":6}]}
winery-shipping-rates
10
winery-total
107
At this point, we need to accurately display the cart when the user goes to the shopping cart page or checkout page:
If the cart’s table is on the shopping cart page, then this method iterates over the array of objects contained in the winery-cart key and populates the table by adding a text field to allow users to modify the quantity of each product. For the sake of simplicity, I didn’t include an action to remove an item from the cart, but that procedure is pretty simple:
Get the items array, contained in session storage.
Get the product’s name, contained in the td element with the pname class.
Create a new array by filtering out the item with the product’s name, obtained in step 2 (you can use $.grep()).
Save the new array in the winery-cart key.
Update the total and shipping charge values.
Then, we need a method that updates the cart with a new quantity value for each product:
Our method loops through all of the relevant table cells of the cart and builds a new object to be inserted in the winery-cart key. It also recalculates the total price and shipping charge by taking into account the newly inserted values of the quantity fields.
Suppose that a user changes the quantity of Wine #2 from 2 to 6:
Key
Value
winery-cart
{“items”:[{"product":"Wine #1","price":5,"qty":5},{"product":"Wine #2","price":8,"qty":6},{"product":"Wine #3","price":11,"qty":6}]}
winery-shipping-rates
20
winery-total
139
If the user wants to empty their cart and start over, we simply have to add the following action:
Now, session storage has been emptied entirely, and the user may start making purchases again. However, if they decide to finalize their order instead, then we need to handle the checkout form when they insert their personal information.
The first thing we need to do is hide the shipping fields if the user checks the toggle that specifies that their billing information is the same as their shipping information. We use the change event, combined with jQuery’s .prop() method. (If you’re curious about the difference between .prop() and .attr(), StackOverflow has a good discussion of it.)
Then, we validate the form by returning a false value in case of errors, thus preventing the form from being submitted. If validation succeeds, we save the user’s data in storage. For example:
Key
Value
winery-cart
{“items”:[{"product":"Wine #1","price":5,"qty":5},{"product":"Wine #2","price":8,"qty":6},{"product":"Wine #3","price":11,"qty":6}]}
winery-shipping-rates
20
winery-total
139
billing-name
John Doe
billing-email
jdoe@localhost
billing-city
New York
billing-address
Street 1
billing-zip
1234
billing-country
USA
The final step is the page with the PayPal form. First, we need to display the user’s information gathered on the checkout page:
Our method first checks whether the user has inputted either billing or shipping information or both. Then, it simply builds an HTML fragment by getting the user’s data from session storage.
Finally, the user may buy the products by submitting the PayPal form. The form redirects them to PayPal, but the fields need to be filled in properly before the form can be submitted.
First, we get some important information from session storage — namely, the shipping rate and the total number of items in the cart. We divide the total shipping amount by the number of items to get the shipping rate for each item.
Then, we set the URL for the action attribute of the form, together with our business email and currency code (taken from the paypalBusinessEmail and paypalCurrency properties, respectively).
Finally, we loop through the items of our cart, and we append to the form several hidden input elements containing the quantities, the names of the products, the number of items for each product, the prices (amounts), and the unit shipping rates.
The monetary values are formatted as 00,00. Explaining all of the possible values of a PayPal form and the various types of PayPal forms goes well beyond the scope of this article, If you want to go deeper, I recommend the following reading:
“HTML Form Basics for PayPal Payments Standard,” PayPal Developer
“HTML Variables for PayPal Payments Standard,” PayPal Developer
Preview And Source Code
The following video shows the result. I’ve omitted PayPal’s landing page to protect my account’s data, but you can see it as a screenshot.
Get the code from the GitHub repository. Just change the paypalBusinessEmail property of the $.Shop object to your PayPal Sandbox email account.
Other Resources
“DOM Storage Guide,” Mozilla Developer Network
“Introduction to Session Storage,” Nicholas C. Zakas
“Using data-* Attributes,” Mozilla Developer Network
(al, ea)
© Gabriele Romanato for Smashing Magazine, 2014.