How to do IndexedDB API 2024

indexeddb api base de datos local html 5 creatuwebpymes blog
k

12/03/2023

IndexedDB API as Local Storage

This article is about the IndexedDB API which is a database locally on your computer. The indexedDB API has been established as standard in applications made with HTML5.

IndexedDB API has a number of advantages compared to traditional databases. For instance, some of them is that you do not have to connect to the server to return information, as a result, the response is faster. On the other hand, it has more flexibility when storing data, since it is not governed by tables.

In this example, we are going to learn how to create a local database on a web page. The user can store information, which in this case, will be book data such as the title, author, year that it was written, and its ISBN. Once this data is stored, the user can also delete a book from this database if he so wishes.

First of all, we create a HTML document. This form will store the information that the user inputs about the books. On the left you see a screenshot of what you see in the browser.

HTML


<!DOCTYPE html>
<html lang="es">
<head>
	<title>Ejercicio 6 Modulo indexedDB</title>
	<meta http-equiv="Content-type" content="text/html" charset="utf-8">
	<script type="text/javascript" src="index++.js"></script>
</head>
<body>
	<div id="contenedor">
		<form id="formulario" name="formulario" method="post" action="">
			<h2>Ejercicio 6 indexedDB</h2>
				<table>
					<tr>
						<td>Titulo</td>
						<td><input type="text" name="titulo" id="titulo"></td>
					</tr>
					<tr>
						<td>ISBN</td>
						<td><input type="text" name="isbn" id="isbn"></td>
					</tr>
					<tr>
						<td>Autor</td>
						<td><input type="text" name="autor" id="autor"></td>
					</tr>
					<tr>
						<td>Año</td>
						<td><input type="text" name="ano" id="ano"></td>
					</tr>
					<tr>
						<td></td>
						<td><input type="submit" name="boton" id="boton" value='Enviar'>
						
					</tr>
				</table>		
		</form>
		<br>
		<br>
		<label>Titulo:</label>
		<input type="text" name="deleteClave" id="deleteClave">
		<input type="submit" name="delete" id='delete' value="Borrar"></td>	
	</div>
</body>
</html>
Formulario visto en navegador relacionado con la API IndexedDB

How to Create the IndexedDB API Database

In addition, there is some javascript code. This code is responsible for the data storage.

Firstly, we declare the variable bd with global scope. This will allow us to use it inside and outside the functions.

Secondly, we put the window object to listen for the load event. As a result, once the page loads, that event is executed. Therefore the iniciar function is activated. This line of code is placed at the end.

window.addEventListener (‘load’, iniciar, false);

Next we declare the variables that correspond to the elements of the html document such as title, isbn, author, etc. The id value of each element is taken into account for its selection.

With indexedDB.open (´Books´, 2); We are creating the Books database and version 2. The result is stored in the request variable.

JS


//declaracion de la variable bd 

var bd;

function iniciar(){

	var titulo = document.getElementById('titulo');
	var isbn = document.getElementById('isbn');
	var autor = document.getElementById('autor');
	var ano = document.getElementById('ano');
	var boton = document.getElementById('boton');
	var borrar = document.getElementById('delete');



	boton.addEventListener('click', agregar, false);
	borrar.addEventListener('click', borrarClave, false);



	var request = indexedDB.open('deusto', 2);
	request.onsuccess = function(e){
		bd = e.target.result;
	}


	request.onupgradeneeded = function(e){
		bd = e.target.result;
		bd.createObjectStore('libros', {keyPath: 'titulo'});
	}
}

Add and Delete Data in IndexedDb API

The agregar function is responsible for collecting the values ​​that are inserted by the user and also for storing them in the DB.

JS


function agregar(){

	var titulo = document.getElementById('titulo').value;
	var isbn = document.getElementById('isbn').value;
	var autor = document.getElementById('autor').value;
	var ano = document.getElementById('ano').value;
	

	var libro = {titulo: titulo, isbn: isbn, autor: autor, ano: ano};

	var customerObjecstore = bd.transaction('libros', 'readwrite').objectStore('libros');
	customerObjecstore.add(libro);
	alert ('Registro guardado con exito en la base de datos');
	return false;
	}

 

The function borrarClave() is responsible for the deletion of the data of the DB of the key that the user indicates.

JS


function borrarClave(){

	var borrar = document.getElementById('deleteClave').value;


	var customerObjecstore = bd.transaction('libros', 'readwrite').objectStore('libros');
	var registro= customerObjecstore.delete(borrar);
	registro.onsuccess = function(e){
		alert('Registro borrado de la base de datos exitosamente');
		return false;
	}
}


window.addEventListener('load', iniciar, false);

 

This post is an HTML exercise many students come across in their initial projects.

There are plenty of articles and tutorials about indexeddb api. However, If you wish to learn more about this subject, here are some ebooks to learn about this local database.

Creatuwebpymes, is a web design company based in Lanzarote – Canary Islands. We ❤️ programming in JavaScript, hence the reason for this post.

creatuwebpymes quien somos

Francisco Brito Diaz

CEO of creatuwebpymes.com, web design and digital marketing company in the Canary Islands