0

Im quite new to this object oriented java script programming.

html5rocks.webdb.insertuser = function(username){
    var db = html5rocks.webdb.db;
    var id;
    db.transaction(function(tx){
        var addedOn = new Date();
        tx.executeSql("INSERT INTO user(name) VALUES (?)",
            [username],
            html5rocks.webdb.onSuccess,
            html5rocks.webdb.onError);
    });
}

here is my code which i got by following a nice tutorial at http://www.html5rocks.com/en/tutorials/webdatabase/todo/

Now the thing i understood is this "onSuccess" is called as a call back. So if i want to get the value as the return parameter of whole function i need to use some sort of a blocking. I would like to know a way to get the insertion id return value

dinesh707
  • 12,106
  • 22
  • 84
  • 134

1 Answers1

1

Most db tables with have an auto-generated id column to identify each row. It’s nice after you perform an insert to get this value back so you can assign it to your object in memory. Turns out it’s super easy:

db = openDatabase(db_name, ‘1.0’, options.description, size);

db.transaction(function(tx) {
  tx.executeSql(“insert into posts (title) VALUES (‘Hear the news’)”, [], function(tx, sql_res) {
    var lastInsertId = sql_res.insertId;
  });
});

Source: http://scottpersinger.com/post/9638490944/html5-web-database-get-the-last-insert-id

Clickbeetle
  • 629
  • 4
  • 13
  • Can you make it to be a JS function. I know it can be set into a variable. But i need whole function to be blocked untill the callback comes in. – dinesh707 Nov 24 '13 at 18:34
  • Sorry, don't quiet understand what you mean. Can you explain it? – Clickbeetle Nov 24 '13 at 20:59
  • value insertId = insertUser("abc"); I need to get the value like this. So if you can show me how to create a function like that its great. Tx – dinesh707 Nov 25 '13 at 07:58
  • 1
    I think you can't do this. Look at this question http://stackoverflow.com/questions/6847697/how-to-return-value-from-callback-function – Clickbeetle Nov 26 '13 at 18:39