0

I have problem to get sqlite data Cordova-sqlite-storage Plugin and put in menu on Cordova app.

See the part of my code:

var db = window.sqlitePlugin.openDatabase({name: "test.db", location: 'default'});

var items = [];

db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM categories', [], function (tx, results) {

    for (i = 0; i < results.rows.length; i++){
        items.push('<li data-page="categories" data-value="'+results.rows.item(i).cat_id+'"><a href="#"><i class="fa fa-'+results.rows.item(i).cat_icon+'"></i><em>'+results.rows.item(i).cat_title+'</em></a></li>');
        alert('<li data-page="categories" data-value="'+results.rows.item(i).cat_id+'"><a href="#"><i class="fa fa-'+results.rows.item(i).cat_icon+'"></i><em>'+results.rows.item(i).cat_title+'</em></a></li>');
    }
}, null);
});

items.push('<li data-page="categories" data-value="aaa"><a href="#"><i class="fa fa-check"></i><em>Teste</em></a></li>');
jQuery('.menu').append(items);

The problem is that the items.push() in the for() does not work. Why?

The alert() in the for() correctly displays the data.

The second items.push() works correctly.

Alisson Linneker
  • 312
  • 1
  • 2
  • 12

1 Answers1

0

You are missing the asynchronous behaviour of your code. Since the transaction to the database is something that takes some time to finish, a callback is provided to listen to this finish with success or error.

In your code :

items.push('<li data-page="categories" data-value="aaa"><a href="#"><i class="fa fa-check"></i><em>Teste</em></a></li>');
jQuery('.menu').append(items); 

This is called before than your callback does.

To solve it you have to move the line of code that handle DOM modifications inside the callback where results are available, just after the for loop :

var db = window.sqlitePlugin.openDatabase({name: "test.db", location: 'default'});

var items = [];

db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM categories', [], function (tx, results) {

    for (i = 0; i < results.rows.length; i++){
        items.push('<li data-page="categories" data-value="'+results.rows.item(i).cat_id+'"><a href="#"><i class="fa fa-'+results.rows.item(i).cat_icon+'"></i><em>'+results.rows.item(i).cat_title+'</em></a></li>');
        alert('<li data-page="categories" data-value="'+results.rows.item(i).cat_id+'"><a href="#"><i class="fa fa-'+results.rows.item(i).cat_icon+'"></i><em>'+results.rows.item(i).cat_title+'</em></a></li>');
    }
    jQuery('.menu').append(items);
}, null);
});
Jose Hermosilla Rodrigo
  • 3,513
  • 6
  • 22
  • 38