DotNetCurry Logo

HTML5 Client Side Storage (Local Storage and Session Storage)

Posted by: Pravinkumar Dabade , on 4/15/2014, in Category HTML5 & JavaScript
Views: 37486
Abstract: In this article we will take a look at HTML5 Client side storage using Local Storage and Session Storage with an example.

For years, developers have used client-side cookies to store data like user preferences, order items etc. However cookies are limited in size and structure (4KB) and they travel with every request to the web server, creating unnecessary overhead. HTML5 provides two client-side storage facilities – web storage (includes local storage and session storage similar to persistent cookie and session cookie) & database storage (SQLite or IndexedDB). Using web storage, you can store upto 5 MB data at client side. This data does not travel with every request to the web server.

 

In this article, we will take a look how to store the data at client side using the two new web storage techniques of HTML5 –

1. Local Storage

2. Session Storage

We will start by creating an application to test the HTML5 local and session storage. Start with Visual Studio or any other Editor like SublimeText and create an empty web site with the name PurchaseOrderSystem as shown below. Since I am using Visual Studio, I have created an empty ASP.NET website

create-html5

Create a HTML page with the name CustomerProfile.html. This page will store the details of the customer who would like to place an order. Write following HTML code in the page –

<!DOCTYPEhtml>
<htmllang="en">
<head>
<title>Customer Profile</title>
</head>
<body>
<sectionid="contact"class="grad">
<h1>Customer Profile Form</h1>
<form>
<table>
<tr>
<tdstyle="width:30%;">First Name</td>
<tdstyle="width:70%;"><inputid="txtFirstName"type="text"placeholder="Enter First Name"autofocus/></td>
</tr>
<tr>
<tdstyle="width:30%;">Last Name</td>
<tdstyle="width:70%;"><inputid="txtLastName"type="text"placeholder="Enter Last Name"/></td>
</tr>
<tr>
<tdstyle="width:30%;">Address</td>
<tdstyle="width:70%;"><inputid="txtAddress"type="text"placeholder="Enter Your Address"/></td>
</tr>
<tr>
<tdstyle="width:30%;">City</td>
<tdstyle="width:70%;"><inputid="txtCity"type="text"placeholder="Enter City Name"/></td>
</tr>
<tr>
<tdstyle="width:30%;">Contact No.</td>
<tdstyle="width:70%;"><inputid="txtContactNo"type="text"placeholder="Enter Contact No."/></td>
</tr>
<tr>
<tdstyle="width:30%;">Email ID</td>
<tdstyle="width:70%;"><inputid="txtEmailID"type="text"placeholder="Enter Email ID"/></td>
</tr>
<tr>
<tdstyle="width:100%;text-align:center;"colspan="2"><inputid="Submit"type="submit"value="Submit Profile"/></td>
</tr>
</table>
</form>
</section>
</body>
</html>


customeroutput

Now let’s write some JavaScript code which will store the data at client side using the HTML5 Session Storage. First add jQuery and Modernizer to our project. If you are using Visual Studio, you can use the NuGet package. Add the reference to the scripts as shown below -

addscript

Now let's add a DOM ready function and write some code as shown below -

<script>
$(function () {
    $("#Submit").click(function () {
        var customerProfile = {
            "FirstName": $("#txtFirstName").val(),
            "LastName": $("#txtLastName").val(),
            "Address": $("#txtAddress").val(),
            "City": $("#txtCity").val(),
            "ContactNo": $("#txtContactNo").val(),
            "EMailID": $("#txtEmailID").val(),
        };
        if (Modernizr.localstorage) {
            var localCustomerProfile = window.localStorage;
            var custProfile=JSON.stringify(customerProfile);
            localCustomerProfile.setItem("Profile", custProfile);
            window.location.href("Orders.html");
        }
    });
});
</script>

In the above function, we are creating a JSON object which holds the values filled by Customer as his/her profile. Then with the help of Modernizer, we are checking the support for local storage in the browser. If the support is there, it will store the JSON object into our local storage using a function setItem. This function allows you store the values in a Key and Value format. Then we use our customer Profile to fill the order form using window object.

Once you are done with the CustomerProfile page, now we will prepare our Orders.html page which will allow user to fill the order form and purchase the product. The page and JavaScript code is as shown below -

<!DOCTYPE html>
<html lang="en">
<head>
<title>Place an Order</title>
<style>
.price{}
</style>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script src="Scripts/modernizr-2.6.2.js"></script>
<script>
$(function () {
    $("#Submit").click(function () {
        var actualPrice=parseFloat($(".price").attr("data-value"));
        var qty=parseInt($('#txtQty').val());
        var calculateTotalPrice = actualPrice * qty;
        var orderData = {
            "OrderID": $("#txtOrderNo").val(),
            "OrderDate": $("#txtOrderDate").val(),
            "RequiredDate": $("#txtRequiredDate").val(),
            "Price":$(".price").attr("data-value"),
            "Qty": $("#txtQty").val(),
            "TotalPrice": calculateTotalPrice,
            "Address": $("#txtShipAddress").val(),
            "City": $("#txtShipCity").val(),
        };
        if (Modernizr.localstorage) {
            var jsonOrder = JSON.stringify(orderData);
            var persistentData = window.localStorage;
            persistentData.setItem("myOrder", jsonOrder);
            window.location.href = "YourCart.html";
        }
       
    });
});
</script>
</head>
<body>
<section id="contact">
<h1>Customer Profile Form</h1>
<table>
<tr>
    <td style="width:30%;">Order No</td>
    <td style="width:70%;"><input id="txtOrderNo" type="text" autofocus /></td>

</tr>
<tr>
    <td style="width:30%;">Order Date</td>
    <td style="width:70%;"><input id="txtOrderDate" type="date" placeholder="Choose Order Date" max="12/12/2013" /></td>
</tr>
<tr>
    <td style="width:30%;">Required Date</td>
    <td style="width:70%;"><input id="txtRequiredDate" type="date" placeholder="Choose Required Date" /></td>
</tr>
<tr>
    <td style="width:30%;">Choose Product</td>
    <td style="width:70%;">
        <select id="selectProduct">
            <option value="Choose Product">Choose Product</option>
            <option value="Laptop" class="price" data-value="25000">Laptop</option>
            <option value="Tablet" class="price" data-value="12000">Tablet</option>
            <option value="Washing Machine" class="price" data-value="15000">Washing Machine</option>
            <option value="Oven" class="price" data-value="16000">Oven</option>
            <option value="LED TV" class="price" data-value="42000">LED TV</option>
        </select>
    </td>
</tr>
<tr>
    <td style="width:30%;">Quantity</td>
    <td style="width:70%;"><input id="txtQty" min="1" max="10" value="1" type="number" /></td>
</tr>

<tr>
    <td style="width:30%;">Shipping Address</td>
    <td style="width:70%;"><input id="txtShipAddress" type="text" /></td>
</tr>
<tr>
    <td style="width:30%;">Shipping City</td>
    <td style="width:70%;"><input id="txtShipCity" type="text" /></td>
</tr>
<tr>
    <td style="width:100%;text-align:center;" colspan="2"><input id="Submit" type="submit" value="Submit Order" /></td>
</tr>
</table>
</section>
</body>
</html>

The above page design looks similar to the following -

orderform

The jQuery DOM ready function will create a JSON object and will store it into our local storage. We are also calculating the total price of the product by multiplying it with the required quantity.

It’s time to display the Order Details with some customer information. For this, we will add one more HTML page with the name YourCart.html. In this web page, we will show the product details with the Customer information. The code is as shown below -

<!DOCTYPE html>
<html lang="en">
<head>
<title>See Your Order Details</title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script src="Scripts/modernizr-2.6.2.js"></script>
<script>
$(function () {
    if (Modernizr.localstorage) {
        var localData = window.localStorage;
        var orderData = JSON.parse(localData.getItem("myOrder"));
        var profile = JSON.parse(localData.getItem("Profile"));

        $('#ContactName').text(profile.FirstName + ' ' + profile.LastName)
        $('#ContactNo').text(profile.ContactNo);
        $("#OrderID").text(orderData.OrderID);
        $("#OrderDate").text(orderData.OrderDate);
        $("#RequiredDate").text(orderData.RequiredDate);
        $("#UnitPrice").text(orderData.Price);
        $("#Qty").text(orderData.Qty);
        $("#TotalPrice").text(orderData.TotalPrice);
        $("#ShippingAddress").text(orderData.Address);
        $("#ShippingCity").text(orderData.City);
    }
});
</script>
</head>
<body>
<div id="orderContainer">
<h1>Your Order Details</h1>
<h2>Total Items in Your Cart</h2>
<h3>Contact Name - [<span id="ContactName"></span>]</h3>
<h3>Contact No   - [<span id="ContactNo"></span>]</h3>
<div>
<table border="1">
<thead>
    <tr>
        <th>Order Id</th>
        <th>Order Date</th>
        <th>Required Date</th>
        <th>Unit Price</th>
        <th>Quantity</th>
        <th>Total Amount</th>
        <th>Shipping Address</th>
        <th>Shipping City</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><span id="OrderID"></span></td>
        <td><span id="OrderDate"></span></td>
        <td><span id="RequiredDate"></span></td>
        <td>$<span id="UnitPrice"></span></td>
        <td><span id="Qty"></span></td>
        <td>$<span id="TotalPrice"></span></td>
        <td><span id="ShippingAddress"></span></td>
        <td><span id="ShippingCity"></span></td>
    </tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

The output of all three pages is as shown below -

customerprofile

filledorder

mycart

Now change the storage code from local storage to session storage. Open CustomerProfile.html page and change the JavaScript code as shown below -

if (Modernizr.sessionstorage) {
    var sessionCustomerProfile = window.sessionStorage;
    var custProfile = JSON.stringify(customerProfile);
    sessionCustomerProfile.setItem("Profile", custProfile);
    window.location.href = "Orders.html";
}

The above code performs a check for session storage and stores the data with the key Profile.

Now open the Orders.html page and replace the If condition as shown below -

if (Modernizr.sessionstorage) {
    var jsonOrder = JSON.stringify(orderData);
    var temporaryData = window.sessionStorage;
    temporaryData.setItem("myOrder", jsonOrder);
    window.location.href = "YourCart.html";
}

And the final code change is in YourCart.html page as shown below -

if (Modernizr.sessionstorage) {
    var sessionData = window.sessionStorage;
    var orderData = JSON.parse(sessionData.getItem("myOrder"));
    var profile = JSON.parse(sessionData.getItem("Profile"));
}

One primary difference between localStorage and sessionStorage is localStorage stores data till the application or user deletes the object, whereas sessionStorage stores data for the duration of a user’s session interaction of with a page.

Now run your CustomerProfile.html page, fill the Customer Profile, then fill the order form and finally you will see the Cart with all the required details.

And that’s how you can use Local Storage and Session Storage to store the data locally at client side.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by 66 on Friday, May 23, 2014 4:59 AM
ewewweew
Comment posted by sa on Tuesday, July 22, 2014 5:22 AM
adadad
Comment posted by Mayank Gaur on Wednesday, November 5, 2014 5:32 AM
Really Nice article;I have doubt how to store particular page details(like recently viewed product) in cookies,could you please suggest