Phonegap: insert query sqlite when login success

I build an mobile app hibrid base with phonegap and jquery mobile. My app has a login system, retrieve data from database in server and insert it to sqlite when login succes, so the app can access to the data even it's offline. i use plugin from litehelpers. And this my sql connect script in database.js:

document.addEventListener("deviceready", connectDB, false);

var kode = JSON.parse(window.localStorage['konfirmasi']);

//create or open Database
function connectDB(){
  db = window.sqlitePlugin.openDatabase("konfirmasi", "1.0", "Data Konfirmasi Pengiriman", "1000");
  db.transaction(populateDB,successCB,errorCB);
}

//create table and insert some record
function populateDB(tx) {
    tx.executeSql("CREATE TABLE IF NOT EXISTS data_konfirmasi (kode_transaksi text, status text) UNIQUE(kode_transaksi)");
}

//function will be called when an error occurred
function errorCB(err) {
    console.log("Error processing SQL: "+err.code);
}

//function will be called when process succeed
function successCB() {
    console.log("Connected to database!");
    //db.transaction(queryDB,errorCB);
}

function insertDB(tx){
    for (var i = kode.length - 1; i >= 0; i--) {
        tx.executeSql("INSERT INTO data_konfirmasi VALUES ("+kode[i]+", 'Belum Terkirim');");
    };
}

function queryDB(){
    db.transaction(insertDB,errorCB,querySuccess);
}

function querySuccess(){
    console.log('Insert query success!');
}

function dropDB(){
    db.transaction(dropQuery,errorDrop,successDrop);
}

function dropQuery(tx){
    tx.executeSql("DROP TABLE IF EXIST data_konfirmasi");
}

function successDrop(){
    console.log('Drop table successful');
}

function errorDrop(err){
    console.log('Drop table unsuccessful, Error code: '+err.code);
}

function selectData(err){
    db.transaction(selectQuery, errorCB, successQuery)
}

function selectQuery(tx){
    tx.executeSql('SELECT * FROM data_konfirmasi',[], querySuccess, errorCB);
}

function querySuccess(tx, results) {
    console.log("Returned rows = " + results.rows.length);
    // this will be true since it was a select statement and so rowsAffected was 0
    if (!results.rowsAffected) {
        console.log('No rows affected!');
        return false;
    }
    // for an insert statement, this property will return the ID of the last inserted row
    console.log("Last inserted row ID = " + results.insertId);
}

Then, when user login for the first time and success it will retrieve data from server with json, and i want my app to insert retrieved data to sqlite. So, how to put the query for login success only? After that i want to make it DROP table and clear localStorage when it's logout. This is my login and logout script (main.js):

$(document).on('pageinit','#login',function(){
    $(document).on('click','#submit',function(){
        if($('#username').val().length>0&&$('#password').val().length>0){
            var un = $('#username').val();
            var pw = $('#password').val();
            $.ajax({
                url:'http://qrkonfirmasi.16mb.com/delivery/login.php',
                data:{  username : un,
                        password : pw
                    },
                type:'post',
                async:'false',
                dataType: 'json',
                beforeSend:function(){
                    $.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
                },
                complete:function(){
                    $.mobile.loading('hide');
                },
                success:function(result){
                    console.log(result);
                    if(result.status==true){
                        user.name=result.message;
                        window.localStorage.setItem('konfirmasi', JSON.stringify(result.data));
                        console.log('Kode: ', JSON.parse(window.localStorage['konfirmasi']));
                    var kode = JSON.parse(window.localStorage['konfirmasi']);
                    console.log('Array length: '+kode.length);
                        queryDB();
                        console.log('Login berhasil');
                        $.mobile.changePage("#konfirmasi");
                        window.localStorage.setItem('uname', un);
                        window.localStorage.setItem('passwd', pw);                        
                        console.log(window.localStorage['uname']);
                    }else{
                        alert('Login gagal. Username atau password tidak sesuai');
                    }
                },
                error:function(request,error){
                    alert('Koneksi error. Silahkan coba beberapa saat lagi!');
                }
            });
        }else{
            alert('Masukkan username dan password!');
        }
        return false;
    });
});

$(document).on('pagebeforeshow','#konfirmasi',function(){
    $.mobile.activePage.find('.welcome').html('<h3>Selamat Datang '+user.name+'</h3>' );
});

$(document).off('click').on('click','#logout',function(){
    window.localStorage.clear();
    dropDB();
    $.mobile.changePage("#home");
});

function exitFromApp(){
    navigator.app.exitApp();
}

So, am i at the right way for logout script? I didn't know it works or not because i still cannot try it because the login script still error when i try it with insert query.

Can someone help me make it done, please?

Answers


Where are u calling this piece of code from?

function insertDB(tx,val){
            for (var i = kode.length - 1; i >= 0; i--) {
                tx.executeSql('INSERT INTO konfirmasi VALUES ('+a[i]+');',querySuccess,errorCB);
            };
        }

If you are calling it from a transaction, then the "val" parameter will not be passed to the insertDB function directly. You might try the following thing:

val = [];
db.transaction(function(tx){
insertDB(tx, val);
}, errorCB);

Moreover, make sure that the stements always run within a db.transaction context

Have fun!


Need Your Help

Add verbosity to rspec's passing expectations

ruby-on-rails rspec

I'm using rspec rails to test my application, but I'm concerned that a few specs may actually be misleading. Can I get more information regarding passing specs in my console output to make sure the...