jskidd3
jskidd3

Reputation: 4783

Variable no longer accessible inside web sql transaction?

The function below is always returning 'Inserted serial: undefined'. I am struggling to realise why it is doing this, if I console.log before the db.transaction then it outputs a serial (just a number). Why is it that inside db.transaction data[i] is suddenly undefined?

  var localSerials = [340, 234, 545, 239, 546];

  function downloadUpdates(localSerials) {
    console.log("Updating local database...");
    $.getJSON("update.php", function(data) {
      for (var i = 0; i < data.length; i++) {
        if (localSerials.indexOf(data[i]) == -1) {
          db.transaction(function (tx) {
            tx.executeSql('INSERT INTO serials (serial) VALUES (' + data[i] + ')');
            console.log("Inserted serial: " + data[i]);
          });
        }
      }
    });
  }

Upvotes: 0

Views: 473

Answers (1)

Kyaw Tun
Kyaw Tun

Reputation: 13161

Your async transaction is inside the for loop, which cause creating many parallel transactions without reusing them. Put transaction outside of the loop and reuse the transaction for all request.

var localSerials = [340, 234, 545, 239, 546];

function downloadUpdates(localSerials) {
  console.log("Updating local database...");
  $.getJSON("update.php", function(data) {
    db.transaction(function (tx) {
      for (var i = 0; i < data.length; i++) {
        if (localSerials.indexOf(data[i]) == -1) {
          tx.executeSql('INSERT INTO serials (serial) VALUES (' + data[i] + ')');
          console.log("Inserted serial: " + data[i]);
        });
      }
    }
  });
}

Upvotes: 1

Related Questions