7

I am trying to call a function that SELECTS values from my Web SQL database. I would like to return the SELECTED values into a variable inside the parent function. But, the variable always returns blank, wether it is global or not.

As you will be able to see the console.log inside the selectRow function logs the correct values from the the database query, but the console.log shows up blank in the initDB function.

I have also noticed that the blank log shows up before the log inside the selectRow function. I have found forums where people are talking about database transactions being asynchronous. I understand that this is why my variable being returned is blank. However, after beating my head against the wall many times I still can't find a way to work around this asynchronous issue.

/** Initialize Database  **/
function initDB(){
  createTable();
  var pleaseWork = selectRow("SELECT * FROM planets;");
  console.log(pleaseWork);
}

/** Select Row from Table **/
function selectRow(query){  
  var result = [];

  db.transaction(function (tx) {
    tx.executeSql(query, [], function(tx, rs){  
      for(var i=0; i<rs.rows.length; i++) {
        var row = rs.rows.item(i)
        result[i] = {
          id: row['id'],
          name: row['name']
        }
      } 
      console.log(result);
    }, errorHandler);
  });  

  return result;
}

3 Answers 3

18

You could change your selectRow() function to accept a callback as a parameter, which it will call with the result rather than returning the result:

/** Initialize Database  **/
function initDB(){ 
   createTable();
   selectRow("SELECT * FROM planets;", function(pleaseWork) {
     console.log(pleaseWork);
     // any further processing here
   });
}  

/** Select Row from Table **/ 
function selectRow(query, callBack){ // <-- extra param
   var result = [];
   db.transaction(function (tx) {
      tx.executeSql(query, [], function(tx, rs){
         for(var i=0; i<rs.rows.length; i++) {
            var row = rs.rows.item(i)
            result[i] = { id: row['id'],
                          name: row['name']
            }
         }
         console.log(result);
         callBack(result); // <-- new bit here
      }, errorHandler);
   });
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. Callbacks are a new concept for me but I'll be sure to learn more about them.
Callbacks are the most difficult concept to get used to when starting with javascript
3

this is tricky because you have a delayed response you need to wait the SQL response before return data, that's why need to pass a callback function

Comments

0

See the site: groups.google.com/forum/?fromgroups#!topic/phonegap/YCRt2HducKg

function loadUniteSelectListe() {
db.transaction(function (tx) {
//populate drop down for unites
    tx.executeSql('SELECT * FROM Unites', [], function (tx, results) {
        var len = results.rows.length; 
        var i=0;
        var txt="";
        for (i = 0; i < len; i++){
            txt=txt + "<option value="+results.rows.item(i).uniteName + ">" + results.rows.item(i).uniteSymbol + "</option>";
        }
        document.getElementById("filtreUniteSelect").innerHTML=txt;
     }, null);
   });

}

related to the following HTML:

Unité:  <select name="filtreUniteSelect" id="filtreUniteSelect" ></select><br/>

with the table: Unites

CREATE TABLE IF NOT EXISTS Unites (uniteID INTEGER PRIMARY KEY AUTOINCREMENT, uniteName TEXT, uniteSymbol TEXT)
    tx.executeSql("INSERT INTO Unites(uniteName,uniteSymbol) VALUES(?, ?)", ['heure', 'h']); //fonctionnel un à la fois
    tx.executeSql("INSERT INTO Unites(uniteName,uniteSymbol) VALUES(?, ?)", ['kilometre', 'km']); //fonctionnel un à la fois
    tx.executeSql("INSERT INTO Unites(uniteName,uniteSymbol) VALUES(?, ?)", ['dollar', '$']); //fonctionnel un à la fois

A+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.