Alisson Alisson - 6 months ago 17
jQuery Question

javascript push() not work on Cordova

I have problem to get sqlite data (https://github.com/litehelpers/Cordova-sqlite-storage) 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.

Answer

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);
});