stackunderflow
stackunderflow

Reputation: 1774

cannot set onsuccess callback for indexeddb add transaction

i get a problem to set the callback function before indexeddb add transaction

os = ...the object store (IDBObjectStore) object assigned here
os.onsuccess = function(){alert('dont mess with Messi')}
os.add({name:'Lionel Messi',team:'FC Barcelona',position:'striker',number:10});

the entry was successfully added to the object store, but the function on onsuccess event won't fired. there's another event called onerror. should i use it instead? i dont think so

don't ask me for 'can you give the error part?' because there's no error at all

Upvotes: 2

Views: 1867

Answers (2)

buley
buley

Reputation: 29208

You're going about your request in the wrong way. There's no error because you're merely adding an onsuccess attribute to an object that will never call it.

You don't add onsuccess callbacks to the object store, you open a transaction on the objectStore and add a listener to that transaction.

For a working example using indexes and transactions, check out this jsfiddle I was recently working through with another StackOverflower.* For a more complex example, see my IndexedDB library.

*Note this fiddle is written to the old (pre-Dec 2011), Chrome IDB implementation. A newer (FF) implementation would use an onupgradeneeded callback but would more or less otherwise be the same.

Upvotes: 2

toske
toske

Reputation: 1754

Looks like your assigning handler to wrong object, onsuccess, onerror, onabort handlers are fired by transaction, not object store itself, so the code would look like:

transaction = database.transaction([storeName], IDBTransaction.READ_WRITE);
 ..
 ..
os = transaction.objectStore(storeName);
transaction.oncomplete = function(e) { //do your stuff here } ;
os.add({ id : 1, name : 'John Doe'});

Can you post a code, how are you getting object store, I guess from transaction (don't know of other ways to do it).Please let me know if code above works. Note that object that you're inserting must have property defined as objectStore's key when creating object store.

Upvotes: 1

Related Questions