HTML5 - SPLessons

HTML5 IndexedDB

Chapter 19

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

HTML5 IndexedDB

HTML5 IndexedDB

shape Introduction

HTML5 IndexedDB is used to store the users data in a browsers and is stronger than the local storage. Following are the concepts covered.

  • About IndexedDB
  • IndexedDB

About IndexedDB

shape Description

IndexedDB is an another form of Web SQL database which is used to store the large amount of data for web applications by which performance of these applications becomes faster. W3C has reported that the Web SQL database is a deplored local storage determination.So, web designer ought not to utilize this innovation any more. Features of the indexeddb as shown below.

IndexedDB

shape Description

In order to enter into the indexedDB, add prefixes to the database to store the data in a browsers code as shown below.

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;        
         window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
         window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange 
         if (!window.indexedDB) {
            window.alert("Your browser doesn't support a stable version of IndexedDB.")
         }

The code below demonstrates creating some data about employee details to the database before creating a database.

const employeeData = [
            { id: "00-01", name: "John", age: 35, email: "john@splessons.com" },
            { id: "00-02", name: "Robort", age: 32, email: "prasad@splessons.com" }
         ];
Now user can able to add developed data to the database by using add() function. The code is as shown below.
function add() {
            var request = db.transaction(["employee"], "readwrite")
            .objectStore("employee")
            .add({ id: "00-03", name: "Johnny", age: 19, email: "Johnny@planet.org" });
            request.onsuccess = function(event) {
               alert("Johnny has been added to your database.");
            }; 
            request.onerror = function(event) {
               alert("Unable to add data\r\nJohnny is aready exist in your database! ");
            }
         }

User can read the entered data and can obtain the data from the database by using get() function.

function read() {
            var transaction = db.transaction(["employee"]);
            var objectStore = transaction.objectStore("employee");
            var request = objectStore.get("00-03");
            
            request.onerror = function(event) {
               alert("Unable to retrieve daa from database!");
            };
            
            request.onsuccess = function(event) {
               // Do something with the request.result!
               if(request.result) {
                  alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
               }
               
               else {
                  alert("Johnny couldn't be found in your database!");
               }
            };
         }

With the help of get() function user can store and retrieve the data from the cursor instead of object as shown in the below code.

function readAll() {
            var objectStore = db.transaction("employee").objectStore("employee");  
            objectStore.openCursor().onsuccess = function(event) {
               var cursor = event.target.result;  
               if (cursor) {
                  alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
                  cursor.continue();
               }  
               else {
                  alert("No more entries!");
               }
            }
        }

Either user can remove the data from the database, by using remove() function, the code is as shown below.

function remove () {
	var request = db.transaction([“employee”], “readwrite”)
.objectStore(“employee”)
.delete(“02”);
request.onsuccess = function(event) {
	alert(“Prasad entry has been removed from your database”);
    };
}

shape Examples

Now the code below demonstrate the complete operations of indexedDB.

<!DOCTYPE html>
<html>
   <head>
   
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <script type="text/javascript">
         
         window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
         
         window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
         window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
         
         if (!window.indexedDB) {
            window.alert("Your browser doesn't support a stable version of IndexedDB.")
         }
         
         const employeeData = [
            { id: "00-01", name: "John", age: 35, email: "john@splessons.com" },
            { id: "00-02", name: "Robort", age: 32, email: "prasad@splessons.com" }
         ];
         var db;
         var request = window.indexedDB.open("newDatabase", 1);
         
         request.onerror = function(event) {
            console.log("error: ");
         };
         
         request.onsuccess = function(event) {
            db = request.result;
            console.log("success: "+ db);
         };
         
         request.onupgradeneeded = function(event) {
            var db = event.target.result;
            var objectStore = db.createObjectStore("employee", {keyPath: "id"});
            
            for (var i in employeeData) {
               objectStore.add(employeeData[i]);
            }
         }
         
         function read() {
            var transaction = db.transaction(["employee"]);
            var objectStore = transaction.objectStore("employee");
            var request = objectStore.get("00-03");
            
            request.onerror = function(event) {
               alert("Unable to retrieve daa from database!");
            };
            
            request.onsuccess = function(event) {
               // Do something with the request.result!
               if(request.result) {
                  alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
               }
               
               else {
                  alert("Johnny couldn't be found in your database!");
               }
            };
         }
         
         function readAll() {
            var objectStore = db.transaction("employee").objectStore("employee");
            
            objectStore.openCursor().onsuccess = function(event) {
               var cursor = event.target.result;
               
               if (cursor) {
                  alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
                  cursor.continue();
               }
               
               else {
                  alert("No more entries!");
               }
            };
         }
         
         function add() {
            var request = db.transaction(["employee"], "readwrite")
            .objectStore("employee")
            .add({ id: "00-03", name: "Johnny", age: 19, email: "Johnny@planet.org" });
            
            request.onsuccess = function(event) {
               alert("Johnny has been added to your database.");
            };
            
            request.onerror = function(event) {
               alert("Unable to add data\r\nJohnny is aready exist in your database! ");
            }
         }
         
         function readAll() {
            var objectStore = db.transaction("employee").objectStore("employee");
            
            objectStore.openCursor().onsuccess = function(event) {
               var cursor = event.target.result;
               
               if (cursor) {
                  alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
                  cursor.continue();
               }
               
               else {
                  alert("No more entries!");
               }
            };
         }
         
      </script>
      
   </head>
   <body>
      
      <button onclick="read()">Read </button>
      <button onclick="readAll()">Read all </button>
      <button onclick="add()">Add data </button>
      <button onclick="remove()">Delete data </button>
      
   </body>
</html>

Result
By running the above code in a preferred browser following output is obtained.

By clicking the above buttons employee details are added and removed as shown in the below image.

When clicked on OK button, another employee details are obtained as shown in the below image.

Summary

shape Points

  • In indexedDB each record have a key and some value.
  • IndexedDB API is layered with query language.
  • User can update and remove the entries.