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.
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- body {
- color: #2E8B57;
- font: 12px Verdana;
- }
- body a {
- color: #8B0000;
- text-decoration: none;
- }
- </style>
- <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.
- 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".
- myidb.indexedDB.db = null;
- myidb.indexedDB.open = function() {
- var request = indexedDB.open("mydb");
- request.onsuccess = function(e) {
- myidb.indexedDB.db = e.target.result;
- };
- request.onfailure = myidb.indexedDB.onerror;
- };
- 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.
- myidb.indexedDB.open = function() {
- var request = indexedDB.open("mydb",
- "Database defined");
- request.onsuccess = function(e) {
- var v = "1.0";
- myidb.indexedDB.db = e.target.result;
- var db = myidb.indexedDB.db;
- if(v!= db.version) {
- var setVrequest = db.setVersion(v);
- setVrequest.onfailure = myidb.indexedDB.onerror;
- setVrequest.onsuccess = function(e) {
- var store = db.createObjectStore("itemslist",
- {keyPath: "timeStamp"});
- myidb.indexedDB.getAllItemslistItems();
- };
- }
- myidb.indexedDB.getAllItemslistItems();
- };
- request.onfailure = myidb.indexedDB.onerror;
- }
- 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.
- myidb.indexedDB.addItemslist = function(itemslistText) {
- var db = myidb.indexedDB.db;
- var trans = db.transaction(["itemslist"], IDBTransaction.READ_WRITE, 0);
- var store = trans.objectStore("itemslist");
- var request = store.put({
- "text": itemslistText,
- "timeStamp" : new Date().getTime()
- });
- request.onsuccess = function(e) {
- myidb.indexedDB.getAllItemslistItems();
- };
- request.onerror = function(e) {
- console.log(e.value);
- };
- };
- 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.
- myidb.indexedDB.getAllItemslistItems = function() {
- var mydb = document.getElementById("items");
- mydb.innerHTML = "";
- var db = myidb.indexedDB.db;
- var trans = db.transaction(["itemslist"], IDBTransaction.READ_WRITE, 0);
- var store = trans.objectStore("itemslist");
- // Get everything in the store;
- var keyRange = IDBKeyRange.lowerBound(0);
- var cursorRequest = store.openCursor(keyRange);
- cursorRequest.onsuccess = function(e) {
- var result = e.target.result;
- if(!!result == false)
- return;
- renderItemslist(result.value);
- result.continue();
- };
- cursorRequest.onerror = myidb.indexedDB.onerror;
- };
- 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:
- function renderItemslist(row) {
- var mydb = document.getElementById("items");
- var li = document.createElement("li");
- var a = document.createElement("a");
- var t = document.createTextNode();
- t.data = row.text;
- a.addEventListener("click", function(e) {
- myidb.indexedDB.deleteItemslist(row.text);
- });
- a.textContent = " [Delete]";
- li.appendChild(t);
- li.appendChild(a);
- mydb.appendChild(li)
- }
- 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.
- myidb.indexedDB.deleteitemslist = function(id) {
- var db = myidb.indexedDB.db;
- var trans = db.transaction(["itemslist"], IDBTransaction.READ_WRITE, 0);
- var store = trans.objectStore("itemslist");
- var request = store.delete(id);
- request.onsuccess = function(e) {
- myidb.indexedDB.getAllItemslistItems(); // Refresh the screen
- };
- request.onerror = function(e) {
- console.log(e);
- };
- };
- 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 :
- function init() {
- myidb.indexedDB.open(); // open displays the data previously saved
- }
- window.addEventListener("DOMContentLoaded", init, false);
- function addItemslist() {
- var itemslist = document.getElementById('itemslist');
- myidb.indexedDB.addItemslist(itemslist.value);
- itemslist.value = '';
- }
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.
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- body
- {
- color: #8B0000;
- font: 14px Arial;
- }
- body a
- {
- color: #8B668B;
- text-decoration: none;
- }
- </style>
- <script>
- var myidb = {};
- var indexedDB = window.indexedDB || window.webkitIndexedDB ||
- window.mozIndexedDB;
- if ('webkitIndexedDB' in window) {
- window.IDBTransaction = window.webkitIDBTransaction;
- window.IDBKeyRange = window.webkitIDBKeyRange;
- }
- myidb.indexedDB = {};
- myidb.indexedDB.db = null;
- myidb.indexedDB.onerror = function(e) {
- console.log(e);
- };
- myidb.indexedDB.open = function() {
- var request = indexedDB.open("itemslists");
- request.onsuccess = function(e) {
- var v = "1.99";
- myidb.indexedDB.db = e.target.result;
- var db = myidb.indexedDB.db;
- transaction;
- if (v!= db.version) {
- var setVrequest = db.setVersion(v);
- Stores
- setVrequest.onerror = myidb.indexedDB.onerror;
- setVrequest.onsuccess = function(e) {
- if(db.objectStoreNames.contains("itemslist")) {
- db.deleteObjectStore("itemslist");
- }
- var store = db.createObjectStore("itemslist",
- {keyPath: "timeStamp"});
- myidb.indexedDB.getAllitemslistItems();
- };
- }
- else {
- myidb.indexedDB.getAllitemslistItems();
- }
- };
- request.onerror = myidb.indexedDB.onerror;
- }
- myidb.indexedDB.additemslist = function
- (itemslistText) {
- var db = myidb.indexedDB.db;
- var trans = db.transaction(["itemslist"],
- IDBTransaction.READ_WRITE);
- var store = trans.objectStore("itemslist");
- var data = {
- "text": itemslistText,
- "timeStamp": new Date().getTime()
- };
- var request = store.put(data);
- request.onsuccess = function(e) {
- myidb.indexedDB.getAllitemslistItems();
- };
- request.onerror = function(e) {
- console.log("Error Adding: ", e);
- };
- };
- myidb.indexedDB.deleteitemslist = function(id) {
- var db = myidb.indexedDB.db;
- var trans = db.transaction(["itemslist"],
- IDBTransaction.READ_WRITE);
- var store = trans.objectStore("itemslist");
- var request = store.delete(id);
- request.onsuccess = function(e) {
- myidb.indexedDB.getAllitemslistItems();
- };
- request.onerror = function(e) {
- console.log("Error Adding: ", e);
- };
- };
- myidb.indexedDB.getAllitemslistItems = function() {
- var itemslists = document.getElementById
- ("itemslistItems");
- itemslists.innerHTML = "";
- var db = myidb.indexedDB.db;
- var trans = db.transaction(["itemslist"],
- IDBTransaction.READ_WRITE);
- var store = trans.objectStore("itemslist");
- Get everything in the store;
- var keyRange = IDBKeyRange.lowerBound(0);
- var cursorRequest = store.openCursor(keyRange);
- cursorRequest.onsuccess = function(e) {
- var result = e.target.result;
- if(!!result == false)
- return;
- renderitemslist(result.value);
- result.continue();
- };
- cursorRequest.onerror = myidb.indexedDB.onerror;
- };
- function renderitemslist(row) {
- var itemslists = document.getElementById
- ("itemslistItems");
- var li = document.createElement("li");
- var a = document.createElement("a");
- var t = document.createTextNode(row.text);
- a.addEventListener("click", function() {
- myidb.indexedDB.deleteitemslist(row.timeStamp);
- }, false);
- a.textContent = " [Delete]";
- li.appendChild(t);
- li.appendChild(a);
- itemslists.appendChild(li)
- }
- function additemslist() {
- var itemslist = document.getElementById("itemslist");
- myidb.indexedDB.additemslist(itemslist.value);
- itemslist.value = "";
- }
- function init() {
- myidb.indexedDB.open();
- }
- window.addEventListener("DOMContentLoaded", init, false);
- </script>
- </head>
- <body>
- <ul id="itemslistItems"></ul>
- <input type="text" id="itemslist" name="itemslist" placeholder="Enter Item" style="width: 200px;" />
- <input type="submit" value="Add itemslist Item" onclick="additemslist(); return false;" />
- </body>
- </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:
Now Enter the text -
Now the text is stored in the Object Store
Now in order to delete the text from Object Store, CLick on the DELETE button.