- 12 minute read
- Ecommerce, HTML5
- Share on Twitter, LinkedIn
With the advent of HTML5, many sites were able to replace the plugin and JavaScript codes with simple and more efficient HTML codes such as audio, video, geolocation, etc. HTML5 tags made the work of developers much easier while improving page load time and site performance. In particular, HTML5 web storage was a game changer, allowing users’ browsers to store user data without using a server. Thus, creating web storage allowed front-end developers to achieve more on their website without knowing or using server-side coding or database.
E-commerce websites in line predominantly use server-side languages like PHP to store user data and pass it from one page to another. Using JavaScript back-end frameworks like Node.js, we can achieve the same goal. However, in this tutorial, we will show you step by step how to create a shopping cart with HTML5 and minor JavaScript code. Other uses of the techniques in this tutorial would be to store user preferences, user favorite content, wish lists, and user settings such as name and password on native websites and mobile apps without using a database. data.
Many traffic websites rely on complex techniques such as server clustering, DNS load balancers, client-side and server-side caching, databases, distributed data and microservices to optimize performance and availability. In fact, the biggest challenge for dynamic websites is getting data from a database and using a server-side language like PHP to process it. However, remote database storage should only be used for essential website content, such as articles and user credentials. Features such as user preferences can be stored in the user’s browser, similar to cookies. Similarly, when you build a native mobile app, you can use HTML5 web storage in conjunction with a local database to increase the speed of your app. Therefore, as front-end developers, we need to explore ways in which we can exploit the power of HTML5 web storage in our applications in the early stages of development.
I have been part of a team developing a large-scale social website, and we use HTML5 web storage a lot. For example, when a user logs in, we store the encrypted user ID in an HTML5 session and use it to authenticate the user to protected pages. We also use this feature to store all new push notifications, such as new chat messages, messages from new websites and feeds, and pass them from page to page. When a social website gets a lot of traffic, full reliance on the server for load balancing may not work, so you need to identify the tasks and data that can be handled by the user’s browser instead of your servers.
Project Background
A shopping cart allows a website visitor to view product pages and add items to their cart. The visitor can review all their items and update their cart (for example, to add or remove items). To achieve this, the website needs to store the visitor’s data and pass it from page to page, until the visitor goes to the checkout page and makes a purchase. Data storage can be done through a server-side language or a client-side language. With a server-side language, the server bears the brunt of data storage, while with a client-side language, the visitor’s computer (desktop, tablet, or smartphone) stores and processes the data. Each approach has its pros and cons. In this tutorial, we will focus on a simple client-side approach, based on HTML5 and JavaScript.
Note: Basic knowledge of HTML5 is required to be able to follow this tutorial. , CSS, and JavaScript.
Project Files
Click here to download the project source files. You can also view a live demo.
HTML5 Web Storage Overview
HTML5 Web Storage allows web applications to store values locally in the browser that can survive the session of the browser. browser, just like cookies. Unlike cookies that must be sent with every HTTP request, web storage data is never transferred to the server; therefore, web storage outperforms cookies in web performance. Also, cookies allow you to store only 4KB of data per domain, while web storage allows at least 5MB per domain. Web storage works like a simple array, mapping keys to values, and has two types:
- Session storageThis stores data in a browser session, where it is available until the browser or browser tab is closed. Popups opened from the same window can see session storage, just like iframes within the same window. However, multiple windows from the same origin (URL) cannot see each other’s session storage.
- Local storageThis stores data in the web browser with no expiration date. Data is available to all windows with the same origin (domain), even when the browser or browser tabs are reopened or closed.
Both types of storage are supported currently with all major web browsers.Note that you cannot pass storage data from one browser to another, even if both browsers are visiting the same domain.
Creating a basic shopping cart
To create our cart shopping cart, we first create an HTML page with a simple cart to display items and a simple form to add or edit the cart. Then we add HTML web storage to it, followed by JavaScript coding. Although we are using HTML5 local storage tags, all the steps are identical to those for HTML5 session storage and can be applied to HTML5 session storage tags. Finally, we’ll go over some jQuery code, as an alternative to JavaScript code, for those interested in using jQuery.
Adding HTML5 Local Storage to Shopping Cart
Our Page HTML is a basic page, with tags for external JavaScript and referenced CSS in the head.
The following is the HTML content that appears in the body of the page:
Add JavaScript to shopping cart
We will create and call the JavaScript function doShowAll() in the onload() event to check browser compatibility and dynamically create the table displaying the storage name-value pair.
Alternatively, you can use JavaScript’s onload event by adding this to your JavaScript code:
window.load=doShowAll();
Or use this for jQuery:
$( window ).load(function() { doShowAll(); });
In the CheckBrowser() function, we would like to check if the browser supports HTML5 storage. Note that this step may not be necessary because most modern web browsers support it.
Within doShowAll(), if the CheckBrowser() function first evaluates for browser compatibility, it will create dynamically the table for the shopping list during page load. You can iterate the keys (property names) of key-value pairs stored in local storage inside a JavaScript loop, as shown below. Based on the storage value, this method populates the table dynamically to display the key-value pair stored in local storage.
Note: You or your framework will have a preferred method to create new DOM nodes and handle events. To keep things clear and focused, our example uses .innerHTML and inline event handlers although we would normally avoid that in production code.
Hint: if you want to use jQuery to to bind data, you can simply override document.getElementById(‘list’).innerHTML = list; with $(‘#list’).html()=list;.
Run and test the shopping cart
In the previous two sections, we added code to the HTML header, and We added HTML to the shopping cart and basket form. We also created a JavaScript function to check browser compatibility and fill the cart with the items in the cart. When populating basket items, JavaScript fetches values from HTML web storage, rather than a database. In this part, we’ll show you how data is inserted into the HTML5 storage engine. That is, we will use HTML5 local storage along with JavaScript to insert new items into the shopping cart, as well as to edit an existing item in the cart.
Note: I have added tips sections below to display jQuery code, as an alternative to JavaScript ones.
We’ll create a separate HTML div element to capture user input and submission. We’ll attach the corresponding JavaScript function in the onClick event for the buttons.
You can set properties on the localStorage object similar to a normal JavaScript object. This is an example of how we can set the local storage property myProperty to the value myValue:
localStorage.myProperty=”myValue”;
You can delete the local storage property like this:
delete localStorage.myProperty;
Alternatively, you can use the following methods to access local storage:
localStorage.setItem(‘propertyName’,’value’); localStorage.getItem(‘propertyName’); localStorage.removeItem(‘propertyName’);
To save the key-value pair, get the value of the corresponding JavaScript object and call the setItem method:
function SaveItem() { var name = document.forms.ShoppingList.name.value; var data = document.forms.ShoppingList.data.value; localStorage.setItem(name, data); doShowAll(); }
Below is the jQuery alternative for the SaveItem function. First, add an ID to the form inputs:
Item: Quantity:
Then, select the form inputs by ID and get their values. As you can see below, it’s much simpler than JavaScript:
function SaveItem() { var name = $(“#name”).val(); var data = $(“#data”).val(); localStorage.setItem(name, data); doShowAll(); }
To update an item in the shopping cart, you must first check if that item’s key already exists in local storage, and then update its value, as shown below:
Next the jQuery alternative is shown.
We will use the removeItem method to remove an item from storage.
Tip: Similar to the previous two functions, you can use jQuery selectors in the RemoveItem function.
There is another method for local storage that allows you to clear all local storage. We call the ClearAll() function in the onClick event of the “Clear” button:
We use the clear method to clear local storage, as shown below:
function ClearAll() { localStorage.clear(); doShowAll(); }
Session Storage
The sessionStorage object works the same way as localStorage. You can replace the previous example with the sessionStorage object to expire the data after a session. Once the user closes the browser window, the storage will be cleared. In short, the APIs for localStorage and sessionStorage are identical, allowing you to use the following methods:
- setItem(key, value)
- getItem(key)</ li
- removeItem(key)
- clear()
- key(index)
- length
Carts Shopping With Arrays and Objects
Because HTML5 web storage only supports single name value storage, you must use JSON or another method to convert your arrays or objects to a single string. You may need an array or object if you have a category and subcategories of items, or if you have a shopping cart with multiple data such as customer information, item information, etc. You just need to implode your array or objects into a string to store in web storage and then explode (or split) them back into an array to display on another page. Let’s look at a basic example of a shopping cart that has three sets of information: customer information, item information, and custom mailing address. First, we use JSON.stringify to convert the object to a string. We then use JSON.parse to reverse it.
Tip: Note that the key name must be unique for each domain.
Summary
In this tutorial, we have learned how to create a shopping cart step by step using HTML5 web storage and JavaScript. We have seen how to use jQuery as an alternative to JavaScript. We’ve also discussed JSON functions like stringify and parse for handling arrays and objects in a shopping cart. You can build on this tutorial by adding more functionality, such as adding product categories and subcategories while storing data in a JavaScript multidimensional array. Also, you can replace all JavaScript code with jQuery.
We’ve seen what else developers can achieve with HTML5 web storage and what other features they can add to their websites. For example, you can use this tutorial to store user preferences, favorite content, wish lists, and user settings like names and passwords on websites and native mobile apps, without using a database.
To To conclude, here are some issues to consider when implementing HTML5 web storage:
- Some users may have privacy settings that prevent the browser from storing data.
- Some Users can use their browser in incognito mode.
- Be aware of some security concerns, such as DNS spoofing attacks, cross-directory attacks, and compromise of sensitive data.
Related Reading
- “Browser Storage Limits and Eviction Criteria”, MDN Web Docs, Mozilla
- “Web Storage”, HTML Living Standard,
- “This Week in HTML 5”, The WHATWG Blog
.