Using IndexedDb in HTML5 to Store Data Within the Browser

Introduction 

 
Porting a database becomes quite complicated sometimes and frequent changes in the schema take a lot of time in making things work okay. Now here IndexedDB is a new technology in HTML5 that can act as an Asynchronous web database within the user's browser. This not only allows the users to use their query within the browser, but this feature is very efficient and finds its best use in working online as well as off-line.
 
Here in this application, you will learn how to create a simple insertion and deletion of text in the browser dynamically and that too without the use of databases like SQL, SQL SERVER, etc.
 
Although this feature is supported in IE10 but latest version of Chrome and firefox also helps this operation.
 
Let's begin with our application. Follow the steps below.
 

Step 1

 
First of all, open your HTML editor. for example notepad. Here I'll be using notepad.
 

Step 2

 
Now the first task is to write the starting DOCTYPE of HTML5. Then write the following lines of code. 
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <style>  
  5.       body {  
  6.         color: #2E8B57;  
  7.         font: 12px Verdana;  
  8.       }       
  9.       body a {  
  10.         color: #8B0000;  
  11.         text-decoration: none;  
  12.       }  
  13.     </style>  
  14.         <script>  
In these lines I have defines a simple cascading style to enhance the appearance.
 

Step 3

 
Now I'll be using JavaScript to do the following task. 
  1. Defining and opening the database: The code below is used to define the database in the following application and opening the database to get ready to accept values from the browser. Write the following lines of code. In this code below we are opening a database called "mydb" and assigned it to IndexedDB variable "db".
    1. myidb.indexedDB.db = null;  
    2. myidb.indexedDB.open = function() {  
    3.   var request = indexedDB.open("mydb");   
    4.   request.onsuccess = function(e) {  
    5.     myidb.indexedDB.db = e.target.result;  
    6.    };   
    7.   request.onfailure = myidb.indexedDB.onerror;  
    8. };  
  2. Now Allowing the database to store objects: The object stores are created inside the "setversion" transaction hence it is a very important part. In the code below you will see how the setversion method is used and object stores can be created only in the setversion transaction and in the onsuccess. Also here we'll be some adding items. These following steps take place.
    • The database is set open already
    • An IDBRequest is executed and returned
    • indexedDB.open method is called
    • If the open request is successful onsuccess callback method is executed
    • Database version is verified and If the version is mismatched then setversion is called and this is the only way to change the database structure.
    • Here we can create or delete the object stores. The object stores are created by calling the "createObjectStore" method. The name and parameters are passed.
    • The parameter passed in the object Store gives a unique identity to the object. Here "keypath " is used to define the unique property like the "timestamp" of the object.
      1. myidb.indexedDB.open = function() {  
      2.   var request = indexedDB.open("mydb",  
      3.     "Database defined");   
      4.   request.onsuccess = function(e) {  
      5.     var v = "1.0";  
      6.     myidb.indexedDB.db = e.target.result;  
      7.     var db = myidb.indexedDB.db;  
      8.       if(v!= db.version) {  
      9.       var setVrequest = db.setVersion(v);  
      10.       setVrequest.onfailure = myidb.indexedDB.onerror;  
      11.       setVrequest.onsuccess = function(e) {  
      12.         var store = db.createObjectStore("itemslist",  
      13.           {keyPath: "timeStamp"});  
      14.         myidb.indexedDB.getAllItemslistItems();  
      15.      };  
      16.     }  
      17.     myidb.indexedDB.getAllItemslistItems();  
      18.   };  
      19.    request.onfailure = myidb.indexedDB.onerror;  
      20. }   
  1. Storing Data to the Object store so created: In this step, the object store that has been created is fetched with some items via add item " method. Also to be noticed thing is that READ_WRITE permission is given to the transaction before the actual addition of items. See the code below.
    1. myidb.indexedDB.addItemslist = function(itemslistText) {  
    2.   var db = myidb.indexedDB.db;  
    3.   var trans = db.transaction(["itemslist"], IDBTransaction.READ_WRITE, 0);  
    4.   var store = trans.objectStore("itemslist");  
    5.   var request = store.put({  
    6.     "text": itemslistText,  
    7.     "timeStamp" : new Date().getTime()  
    8.   });  
    9.   request.onsuccess = function(e) {  
    10.     myidb.indexedDB.getAllItemslistItems();  
    11.   };  
    12.   request.onerror = function(e) {  
    13.     console.log(e.value);  
    14.   };  
    15. };  
  2. Retrieving the data from the object store: In the lines of code below you'll know how to retrieve the data stored in the object-store. For this.
    • A method named "getItem" is defined which retrieves the items from the object-store.
    • The READ_WRITE permission is granted
    • The initial position of the item is received by IDBKeyRange.lowerBound(0) method.
    • This initial position is used to retrieve Item form starting.
    • If the request for retrieval is successful then the value is received otherwise control returns.
      1. myidb.indexedDB.getAllItemslistItems = function() {  
      2.   var mydb = document.getElementById("items");  
      3.   mydb.innerHTML = "";    
      4.   var db = myidb.indexedDB.db;  
      5.   var trans = db.transaction(["itemslist"], IDBTransaction.READ_WRITE, 0);  
      6.   var store = trans.objectStore("itemslist");   
      7.   // Get everything in the store;  
      8.   var keyRange = IDBKeyRange.lowerBound(0);  
      9.   var cursorRequest = store.openCursor(keyRange);  
      10.   cursorRequest.onsuccess = function(e) {  
      11.     var result = e.target.result;  
      12.     if(!!result == false)  
      13.       return;  
      14.     renderItemslist(result.value);  
      15.     result.continue();  
      16.   };   
      17.   cursorRequest.onerror = myidb.indexedDB.onerror;  
      18. };  
  1. Rendering the Items: This is used to use the data in a manner easily readable by the user. Here a button for deleting the item is also created. see the code below:
    1. function renderItemslist(row) {  
    2.   var mydb = document.getElementById("items");  
    3.   var li = document.createElement("li");  
    4.   var a = document.createElement("a");  
    5.   var t = document.createTextNode();  
    6.   t.data = row.text;  
    7.   a.addEventListener("click", function(e) {  
    8.     myidb.indexedDB.deleteItemslist(row.text);  
    9.   });  
    10.   a.textContent = " [Delete]";  
    11.   li.appendChild(t);  
    12.   li.appendChild(a);  
    13.   mydb.appendChild(li)  
    14. }    
  2. Now applying query for deleting the item from the Object store: This is a very simple way to remove the item from the Object store.
    • First, the data is inserted into the Object store.
    • READ_WRITE permission is granted
    • Reference to the data is created
    • Delete command is used to delete the data from the store.
      1. myidb.indexedDB.deleteitemslist = function(id) {  
      2.   var db = myidb.indexedDB.db;  
      3.   var trans = db.transaction(["itemslist"], IDBTransaction.READ_WRITE, 0);  
      4.   var store = trans.objectStore("itemslist");  
      5.   var request = store.delete(id);  
      6.   request.onsuccess = function(e) {  
      7.     myidb.indexedDB.getAllItemslistItems();  // Refresh the screen  
      8.   };   
      9.   request.onerror = function(e) {  
      10.     console.log(e);  
      11.   };  
      12. };  
       
  1. Rendering: Now in order to render the previous data in the store and remove the data from the database, when the page loads, write the following code :
    1. function init() {  
    2.   myidb.indexedDB.open(); // open displays the data previously saved  
    3. }   
    4. window.addEventListener("DOMContentLoaded", init, false);  
    5. function addItemslist() {  
    6.   var itemslist = document.getElementById('itemslist');   
    7.   myidb.indexedDB.addItemslist(itemslist.value);  
    8.   itemslist.value = '';  
    9. }  

Step 4

 
Now Javascript is ready, CSS is ready, just need to close the eHtml tags properly. Below is the complete code for working on this application.
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <style>  
  5.         body  
  6.         {  
  7.             color: #8B0000;  
  8.             font: 14px Arial;  
  9.         }        
  10.         body a  
  11.         {  
  12.             color: #8B668B;  
  13.             text-decoration: none;  
  14.         }  
  15.     </style>  
  16.         <script>  
  17.       var myidb = {};  
  18.       var indexedDB = window.indexedDB || window.webkitIndexedDB ||  
  19.                       window.mozIndexedDB;    
  20.       if ('webkitIndexedDB' in window) {  
  21.         window.IDBTransaction = window.webkitIDBTransaction;  
  22.         window.IDBKeyRange = window.webkitIDBKeyRange;  
  23.       }       
  24.       myidb.indexedDB = {};  
  25.       myidb.indexedDB.db = null;      
  26.       myidb.indexedDB.onerror = function(e) {  
  27.         console.log(e);  
  28.       };      
  29.       myidb.indexedDB.open = function() {  
  30.         var request = indexedDB.open("itemslists");      
  31.         request.onsuccess = function(e) {  
  32.           var v = "1.99";  
  33.           myidb.indexedDB.db = e.target.result;  
  34.           var db = myidb.indexedDB.db;  
  35.         transaction;  
  36.           if (v!= db.version) {  
  37.             var setVrequest = db.setVersion(v);  
  38.       Stores  
  39.             setVrequest.onerror = myidb.indexedDB.onerror;  
  40.             setVrequest.onsuccess = function(e) {  
  41.               if(db.objectStoreNames.contains("itemslist")) {  
  42.                 db.deleteObjectStore("itemslist");  
  43.               }   
  44.               var store = db.createObjectStore("itemslist",  
  45.                 {keyPath: "timeStamp"});  
  46.               myidb.indexedDB.getAllitemslistItems();  
  47.             };  
  48.           }  
  49.           else {  
  50.             myidb.indexedDB.getAllitemslistItems();  
  51.           }  
  52.         };      
  53.         request.onerror = myidb.indexedDB.onerror;  
  54.       }        
  55.       myidb.indexedDB.additemslist = function  
  56. (itemslistText) {  
  57.         var db = myidb.indexedDB.db;  
  58.         var trans = db.transaction(["itemslist"],   
  59. IDBTransaction.READ_WRITE);  
  60.         var store = trans.objectStore("itemslist");   
  61.         var data = {  
  62.           "text": itemslistText,  
  63.           "timeStamp"new Date().getTime()  
  64.         };   
  65.         var request = store.put(data);     
  66.         request.onsuccess = function(e) {  
  67.           myidb.indexedDB.getAllitemslistItems();  
  68.         };      
  69.         request.onerror = function(e) {  
  70.           console.log("Error Adding: ", e);  
  71.         };  
  72.       };         
  73.       myidb.indexedDB.deleteitemslist = function(id) {  
  74.         var db = myidb.indexedDB.db;  
  75.         var trans = db.transaction(["itemslist"],   
  76. IDBTransaction.READ_WRITE);  
  77.         var store = trans.objectStore("itemslist");    
  78.         var request = store.delete(id);      
  79.         request.onsuccess = function(e) {  
  80.           myidb.indexedDB.getAllitemslistItems();  
  81.         };       
  82.         request.onerror = function(e) {  
  83.           console.log("Error Adding: ", e);  
  84.         };  
  85.       };        
  86.       myidb.indexedDB.getAllitemslistItems = function() {  
  87.         var itemslists = document.getElementById   
  88. ("itemslistItems");  
  89.         itemslists.innerHTML = "";      
  90.         var db = myidb.indexedDB.db;  
  91.         var trans = db.transaction(["itemslist"],   
  92. IDBTransaction.READ_WRITE);  
  93.         var store = trans.objectStore("itemslist");  
  94.        Get everything in the store;  
  95.         var keyRange = IDBKeyRange.lowerBound(0);  
  96.         var cursorRequest = store.openCursor(keyRange);       
  97.         cursorRequest.onsuccess = function(e) {  
  98.           var result = e.target.result;  
  99.           if(!!result == false)  
  100.             return;   
  101.           renderitemslist(result.value);  
  102.           result.continue();  
  103.         };        
  104.         cursorRequest.onerror = myidb.indexedDB.onerror;  
  105.       };        
  106.       function renderitemslist(row) {  
  107.         var itemslists = document.getElementById    
  108. ("itemslistItems");  
  109.         var li = document.createElement("li");  
  110.         var a = document.createElement("a");  
  111.         var t = document.createTextNode(row.text);       
  112.         a.addEventListener("click"function() {  
  113.           myidb.indexedDB.deleteitemslist(row.timeStamp);  
  114.         }, false);      
  115.         a.textContent = " [Delete]";  
  116.         li.appendChild(t);  
  117.         li.appendChild(a);  
  118.         itemslists.appendChild(li)  
  119.       }       
  120.       function additemslist() {  
  121.         var itemslist = document.getElementById("itemslist");  
  122.         myidb.indexedDB.additemslist(itemslist.value);  
  123.         itemslist.value = "";  
  124.       }       
  125.       function init() {  
  126.         myidb.indexedDB.open();  
  127.       }        
  128.       window.addEventListener("DOMContentLoaded", init, false);  
  129.     </script>  
  130.     </head>  
  131.     <body>  
  132.         <ul id="itemslistItems"></ul>  
  133.         <input type="text" id="itemslist" name="itemslist" placeholder="Enter Item" style="width: 200px;" />  
  134.         <input type="submit" value="Add itemslist Item" onclick="additemslist(); return false;" />  
  135.     </body>  
  136. </html>  

Step 5

 
Save this file as indexDB.HTML and then run this in your browser with the latest version. the output is as below:
 
 output1.gif
 
Now Enter the text -
 
output2.gif
 
Now the text is stored in the Object Store
 
output3.gif
 
Now in order to delete the text from Object Store, CLick on the DELETE button.
 
output1.gif