1

I'm trying to query a WebSQL database using Javascript to return the value of the 'id' column for the single highest data line.

db.transaction(function(tx) {
   //
   // PROBLEM AREA
   // How to get the data into a variable?
   //

   var xyz = 0;

   tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC' [],function(tx, results) {
     var xyz = results.row.id, i;
     alert('Alert 2');
     alert(xyz);
   });

}, function(){
    alert('success SELECTING!');
}); // End transaction

I believe the query is executing as I am getting the success SELECTING alert. The alert(xyz) is simply returning value nil.

How can I get the data from the SQL database into a Javascript variable?

Thanks!

EDIT: The following suggested code change results in a ReferenceError: Can't find variable: results

function myTransaction(cb)
{
    db.transaction(function(tx) {
        tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC', [], function(tx, results) {
        cb(results); }); 
    },function(){
        alert('success SELECTING!');
    }); // End transaction
}

myTransaction(function(results) { alert(results); });
3
  • You need to use callbacks.. Commented Mar 13, 2016 at 16:54
  • function myTransction(cb) { db.transaction(function(tx) { var xyz = 0; tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC' [], function(tx, results) { cb(results); }); }) } myTransction(function(results) { console.log(results); }); Commented Mar 13, 2016 at 16:54
  • Rayon - thanks for your help. Unfortunately that code still isn't doing what I was hoping it would. It's returning a ReferenceError: Can't find variable: results in the console. I will edit the main post to reflect the adjusted code. Commented Mar 13, 2016 at 17:14

1 Answer 1

2

A few things to note:

You're missing a comma in your executeSql parameter list

tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC', [],function(tx, results) {

NOT

tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC' [],function(tx, results) {

The results object contains a rows attribute, not a row.

So you want to use

results.rows.item(0)

NOT

results.row

transaction() takes 3 callbacks, the first is the callback which will be executed when the transaction is opened. The second is the error callback and the third is the success callback. You're using the error callback but treating it like a success callback.

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting tschaible - so my success selecting is in fact not successful? All my notes here suggested I was doing that bit right! That's unfortunate as I have a query before this that is also not working then.

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.