I have been working with IndexedDB for a bit now and I can successfully create a new database, create a store, and add a value during the "on upgrade needed". What I don't understand is, does the database remain "open" or do you have to re-open it inside of every function that needs access to read/write information in the database?
For example, here's my code (which works) to create a new database, and insert one record:
$(document).ready(function() {
var db;
function initDB() {
console.log("opening db...");
var req = indexedDB.open(dbName, version);
req.onsuccess = function(event) {
db = this.result;
console.log("opening db is done");
}
req.onerror = function(event) {
console.log("error opening db: ", event.target.errorCode);
}
req.onupgradeneeded = function(event) {
db = event.target.result;
var store = db.createObjectStore("creds", { autoincrement: true });
store.add({ username:'none', password:'none'}, 1);
}
}
What is causing me confusion is, when I need to access the records in that database, or add more records, or delete records, I thought I could just create a new function and insert some values. This is what I have (which fails):
function saveCreds() {
usr = $("#username").val();
psw = $("#password").val();
$.getJSON(baseURL + "cred-check/?callback=?", { username:usr, password:psw }, function(data) {
if (data.creds_good == 'true'); {
// NEXT LINE FAILS
var store = db.transaction(['creds'], 'readwrite').objectStore('creds');
var request = store.get(1);
request.onsuccess = function (event) {
var data = request.result;
data.username = usr;
data.password = psw;
var requestUpdate = store.put(data, 1);
requestUpdate.onerror = function(event) {
console.log("error putting value...");
}
}
}
});
}
This saveCreds
and the initDB
function are inside the $(document).ready()
function and the db
variable is declared outside the initDB
and saveCreds
functions, but inside the $(document).ready()
so I think my scope was OK.
The problem is, the db
variable is undefined. I get the error: Cannot call method "transaction" of undefined
.
So does this mean that for every function that needs access to the data in the database, I need to reopen it, and reassign it to a variable so I can manipulate/read data in the database?
See Question&Answers more detail:
os