Using HTML5 local storage to retain data after closing the browser

In this tutorial I’m going to show you how to use HTML5 local storage.
HTML5 local storage is used to store data on the clients machine and is pretty much the same with jQuery cookies which I previously wrote about.

Remember inputted data using jQuery cookies

If you want to learn more about HTML5 local storage you can read the awesome book by Mark Pilgrim on HTML5.

Local Storage for Web Applications

Now you don’t have to use a jQuery plugin in order to persist data even after closing the browser as long as the browser supports local storage. You can check if your browser supports local storage on the link below.

Local Storage Support

Here are a few blog post about localStorage performance that you might want to read before you try to implement it in your projects. As a summary, localStorage performs better than cookies, localStorage doesn’t have the same storage space for different browsers and lastly, localStorage isn’t fast. If you want to know more of the details then read the blog posts below.


Mini Project

So that I won’t end up repeating what has already been written about local storage I decided to hit two birds with one stone by showing you how to build a simple application that uses local storage. In this tutorial were going to build a component of a point of sale system which is the adding of stocks.
We are going to use local storage to retain whatever it is that the user has inputted.
This is useful in cases when there is a power interruption while there is a transaction that is currently in progress. Not having to input the data over again will save the user some time in repeating the transaction all over again.



Let’s start by fetching all the items from our database. We also need a button for reloading the inputted data into the text fields for adding stocks, clicking this button will fetch the data in the local storage and load it into the text fields. We also need a clear button which will be used to clear the local storage, clicking this button deletes every data that is on the local storage. Finally we need to have a button for committing the changes in the quantity of the products into the database.

<h3>ADD STOCKS</h3>
$products = $db->get_results("SELECT * FROM products"); 
<input type="button" id="btn_refill" value="Local Storage"/>
<input type="button" id="btn_clear" value="Clear"/>
	<table border="1">
		<th>add qty</th>
	<?php foreach($products as $k=>$v){ ?>
		<td><?php echo $v->product_name; ?></td>
		<td data-id="<?php echo $v->product_id; ?>"><?php echo $v->quantity; ?></td>
		<td><input type="text" name="add_qty[]" data-qty="<?php echo $v->quantity; ?>" id="<?php echo $v->product_id; ?>"/></td>
	<?php } ?>
	<input type="button" id="btn_addstocks" value="Commit Changes"/>
<?php } ?>


Set Item

Next we need to set the items that we are going to save in the local storage every time the text field for entering the additional stocks loses its focus. This means that every time the user makes changes to the additional stocks the local storage also changes.

$('input[type=text]').blur(function(){ var product_id_r = []; //array for storing product id var product_qty_r = []; //array for storing product qty var old_qty_r = []; //array for storing addl qty var index = 0;


//loop through each additional qty $('input[type=text]').each(function(){ if($.trim($(this).val()) != ''){ var qty = $(this).attr('data-qty'); var add_qty = $.trim($(this).val()); var new_qty = parseInt(qty) + parseInt(add_qty); product_id_r[index] = $.trim($(this).attr('id')); old_qty_r[index] = add_qty; product_qty_r[index] = new_qty; index++; } }); //save the products ids, additional qty, and

//updated qty into the local storage localStorage['product_id'] = product_id_r; localStorage['old_qty'] = old_qty_r; localStorage['product_qty'] = product_qty_r; });

As you can see from the code above, we are actually storing the product id, additional quantities and updated quantities(quantity before the update + additional quantity) in a separate array and then assign that array into a local storage item. This is done by looping through all the text fields for additional quantity that is not empty.



Next we write the code for refilling the text fields for additional quantity. First we check if the product_id item on the local storage exists. The double exclamation point forces the result to boolean data type so if the product_id item exist then the has_local variable will have a value of true if not then it will have false stored in it. Remember that local storage can only store key-value pairs which means that it can only store data of type string, but that’s not a reason not to use it since we can use the split() function in JavaScript to do the dirty work for us. Earlier we assigned an array to a local storage item, which means that our local storage item has stored a string similar to the one below.


We just need to use the split() function and supply comma(,) as the separator and voila! instant array that we could loop through. If you have read the code for fetching the items you might have noticed that I used the product id as the id attribute for each of the items we will just have to use that id to pinpoint where we are going to place the additional quantity. For that we will need to loop through all the product ids, note that the product ids that was stored in our local storage are the product ids of items that has additional quantities, the rest that are untouched is not included. To further elaborate what I just said here’s a screenshot. What I have been talking about is that only the product id for guava and apple will be stored in the local storage since they are the only ones that has additional quantities.


Here’s the code.

	var has_local = !!localStorage['product_id'];
	if(has_local == true){
		var product_id_r = localStorage['product_id'].split(',');
		var product_qty_r = localStorage['old_qty'].split(',');
		for(var x in product_id_r){
			var qty = product_qty_r[x];
		alert('No Data present on local Storage');



If you want to clear the local storage you can do so by calling the clear() method for local storage. Note that this will delete all the data on the local storage. I don’t know of a way to clear individual items so if you know then please share it in the comments.



Add Stocks – Front-End

Next is the code for adding stocks. This is similar to what we did when filling the text fields with data that is on the local storage. But since jQuery is awesome we don’t have to loop through all the product ids and call the add_stocks.php a million times. All we have to do is to pass in an array to add_stocks.php and add_stocks.php will take care of the looping for us.
We supplied an array so why do I still see a for loop in the code below? Good question!, the for loop is actually used for updating the quantity that is being shown to the user and we did all that without refreshing the page.

$('#btn_addstocks').click(function(){ var product_id_r = localStorage['product_id'].split(','); var product_qty_r = localStorage['product_qty'].split(','); $.post('add_stocks.php',

{'id_r' : product_id_r, 'qty_r' : product_qty_r}, function(){

//update the quantity on the table

//without page refresh for(var x in product_id_r){ var product_id = product_id_r[x]; var product_qty = product_qty_r[x]; $("td[data-id="+ product_id +"]").text(product_qty); } } ); $('input[type=text]').val(''); localStorage.clear(); });


Add Stocks – Back-End

Here’s the code for updating the stocks in the database.

$product_id_r = $_POST['id_r']; //product id array $product_qty_r = $_POST['qty_r'];//new product qty array //loop through all the update product ids foreach($product_id_r as $k=>$v){ $product_id = clean($v); $product_qty = clean($product_qty_r[$k]); $db->query("UPDATE products SET quantity='$product_qty'

WHERE product_id='$product_id'"); } //escape quotes and other malicious characters function clean($str){ return mysql_real_escape_string($str); }



That’s it! HTML5 Local Storage is actually pretty useful for transactional systems, as I have said earlier, repeating a particular transaction if there is a sudden power interruption is not that efficient especially if the user is catering to hundreds of people in a day. Being able to restore everything that has been inputted will save some time in the part of the user.

2 thoughts on “Using HTML5 local storage to retain data after closing the browser

  1. Nice post. Do you have the demo hosted somewhere, or maybe a screen cast of it?
    As you’re promoting/experimenting with HTML5, have you considered using WebSockets for the communication with your back-end?
    A slightly different aspect of stocks; but you may want to check out this demo highlighting the power of WebSockets: Lightning Fast Stock Trade – WebSocket Portfolio Demo:

    • Unfortunately I don’t have a demo of it, but I’m planning of adding a demo for every article such as this one so people will have a better understanding on how it works.
      It’s actually my first time hearing about WebSockets I’ll try to look into it, thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s