SQlite database with PhoneGap and JavaScript - javascript

I'm using PhoneGap and a SQLite Database.
I try something like this:
I have a function useSavedThing():
function useSavedThing() {
alert("BEFORE getSavedThing()");
getSavedThing();
alert("AFTER getSavedThing()");
}
and a function getSavedThing():
function getSavedThing(){
alert("ONE");
var db = window.openDatabase("Database", "1.0", "Database", 200000);
db.transaction(populateDB, errorCB, successCB);
alert("TWO");
function populateDB(tx) {
alert("THREE");
}
function errorCB(tx, err) {
alert("Error processing SQL: " + err);
}
function successCB() {
alert("FOUR");
db.transaction(getData);
}
function getData(tx) {
alert("FIVE");
tx.executeSql('SELECT * FROM SETTINGS', [], getIt, errorCB);
}
function getIt(tx, results) {
alert("SIX");
var savedthing = results.rows.item(0).data;
}
}
The problem is that when the function getSavedThing() is called, only the first two alerts (alert("ONE"), alert("TWO)) issued but then the alert ("AFTER getSavedThing ()") called.
But I want that all expenses alert ("ONE"), alert ("TWO"), alert ("THREE") alert ("FOUR") alert ("FIVE"), alert ("SIX"), issued before the alert("AFTER getSavedThing()"); appers.
The order fo the alerts should be:
alert("BEFORE getSavedThing()");
alert("ONE");
alert("TWO");
alert("THREE");
alert("FOUR");
alert("FIVE");
alert("SIX");
alert("BEFORE getSavedThing()");
Can someone help me?

Database operations are performed asynchronously. If you want alert("AFTER getSavedThing()") to be executed after the last database operation it needs to be called from the callback function getIt();
function useSavedThing() {
alert("BEFORE getSavedThing()");
var afterGet = function(){
alert("AFTER getSavedThing()");
}
getSavedThing( afterGet ); /*pass the callback function to getSavedThing*/
}
function getSavedThing( callback ){
alert("ONE");
var db = window.openDatabase("Database", "1.0", "Database", 200000);
db.transaction(populateDB, errorCB, successCB);
alert("TWO");
function populateDB(tx) {
alert("THREE");
}
function errorCB(tx, err) {
alert("Error processing SQL: " + err);
}
function successCB() {
alert("FOUR");
db.transaction(getData);
}
function getData(tx) {
alert("FIVE");
tx.executeSql('SELECT * FROM SETTINGS', [], getIt, errorCB);
}
function getIt(tx, results) {
alert("SIX");
var savedthing = results.rows.item(0).data;
callback.call(); /*execute the callback function*/
}
}

You can use this framework for data access in PhoneGap, you will find it quite easy to use:
var db = new MyDB();
//query all users
var users = db.Users.toArrary(callback);

Related

WebSQL - Check database for records (javascript)

I am working on a phonegap app, and have so far set-up the database to which I have the insert and delete function's working correctly.
I am now struggling on checking input values with the data in the database, so for example for now I am just simply attempting to check if any rows are returned, and if there is that will mean the user and pass entered are in the database, if no rows are returned then the user and pass is false.
I am not getting any errors from the sql statement (function errorCB), as well I did put an debug alert within the function LoginSuccess and that worked, however after removing the debug alert in the LoginSuccess function, I do not get prompted with any alerts and instead the page just refreshes.
I have removed the delete and insert functions from the code as it's relevant to this issue.
Any help will be much appreciated.
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(createDB, errorCB, successCB);
}
function createDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS mahdi (FirstName text, LastName text, Email text, Password text)');
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
alert("Database Ready");
}
function loginUser()
{
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(loginDB, errorCB, LoginSuccess);
}
function loginDB(tx)
{
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'");
} function LoginSuccess(tx, results) {
if (results.rows.length > 0) {
alert ("User and Pass Found");
}
else
{
alert ("User and Pass incorrect");
}
}
Don't worry, all fixed. See below if you'd like to see what I changed around. Seem's as though it was the missing array [] in the executesql statement and calling the renderList (changed from loginSuccessful) into the exectutesql statementent.
function loginDB(tx)
{
alert("yep yep yep");
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'", [], renderList);
}
function renderList(tx,results) {
if (results.rows.length > 0) {
navigator.notification.alert("User and Pass Found");
}
else
{
navigator.notification.alert("User and Pass incorrect");
}
}

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?
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!

Having an Error processing SQL:0 PhoneGap SQL

I created an android app using html5 and phonegap and
I have a problem in inserting data into database..
this is my code
document.addEventListener("deviceready", onDeviceReady(), false);
var db;
function onDeviceReady(){
db = window.openDatabase("Libsys", "2.0", "LibraryDB", 200000); //will create database Dummy_DB or open it
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Borrowinfo(id INTEGER PRIMARY KEY AUTOINCREMENT, IDno TEXT NOT NULL, Name TEXT NOT NULL, course TEXT NOT NULL, author TEXT NOT NULL, title TEXT NOT NULL, date_start TEXT NOT NULL, date_return TEXT NOT NULL)');
}
function queryDB(tx){
tx.executeSql('SELECT * FROM Borrowinfo', [], querySuccess, errorCB);
}
function querySuccess(tx,results){
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
$("#Lists").append("<li><a href='#'>"+row['Name']+" "+row['course']+"</a></li>");
}
$("#Lists").listview("refresh");
}
function SaveContacts(idno,fullname,course,author,title,dstart,dreturn){
//alert(""+idno+" "+fullname+"");
db.transaction(function(tx){
var idno = document.getElementById("idno").value;
var fullname = document.getElementById("names").value;
var course = document.getElementById("course").value;
var author = document.getElementById("author").value;
var title = document.getElementById("title").value;
var dstart = document.getElementById("dstart").value;
var dreturn = document.getElementById("dreturn").value;
tx.executeSql('INSERT INTO Borrowinfo(IDno,name,course,author,title,date_start,date_return) VALUES (?,?,?,?,?,?,?)', [idno,fullname,course,author,title,dstart,dreturn], querySuccess);
alert("Record Save!");
});
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB,errorCB);
}
im having an error in the function querySuccess.. the error message is (undefined is not a function querySuccess)
Please, correct me and also help me to fixed the error...
thank you..

Error processing SQL:0 PhoneGap SQL

Im trying out and copied code from here:
http://luthfihariz.wordpress.com/2011/10/23/android-sqlite-phonegap-jquerymobile/
To succeed with a sample I'm working on just to learn this.
I have a link to my complete index.html on pastebin.
Please, correct me and also help me finding this errror.
Link to Pastebin here
I didn't have a lot of time, and it's soon xmas :) But.. :) I did write you a working example with your code as a starter.
Using Cordova version 2.2.0
Using PhoneGap to compile
I did test it on an android device
I did change some things here and there, but I used the code frome here as a reference.
document.addEventListener("deviceready", onDeviceReady, false);
var db = "";
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS SoccerPlayer');
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (Name TEXT NOT NULL, Club TEXT NOT NULL)');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Alexandre Pato", "AC Milan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Van Persie", "Arsenal")');
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM SoccerPlayer', [], querySuccess, errorCB);
}
function querySuccess(tx,result){
var playerlist = document.getElementById("SoccerPlayerList");
var players = "";
alert("The show is on");
var len = result.rows.length;
for (var i=0; i<len; i++){
alert(result.rows.item(i).Name + result.rows.item(i).Club);
players = players + '<li><p class="record">'+result.rows.item(i).Name+'</p><p class="small">Club '+result.rows.item(i).Club+'</p></li>';
}
playerlist.innerHTML = players;
$("#SoccerPlayerList").listview("refresh");
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB, errorCB);
}
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}

Retrieving value from database in Javascript

I am new to mobile application development with PhoneGap. I have created a form to add and show name, address and phone number of a student in SQLite database. But the problem is I don't know to retrieve and display the values in the text boxes.
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
function add(tx){
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name+"','"+address+"','"+phone+"')');
//tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function show(tx){
var name=document.getElementById('n');
tx.executeSql('SELECT * FROM DEMO WHERE (sname='"+name+"')');
document.f.n.value=name;
document.f.a.value=//??;
document.f.p.value=//??;
}
</script>
</head>
<body>
<form name="f" method="get" action="">
Name :<input type="text" id="n" size="10"></input><br>
Add :<input type="text" id="a" size="10"></input><br>
Phone :<input type="text" id="p" size="10"></input><br>
<input type="button" value="Add" onClick="add()">
<input type="button" value="Show" onClick="show()">
</form>
</body>
</html>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
alert("onDeviceReady called");
}
function populateDB(tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name.value+"','"+address.value+"','"+phone.value+"')');
}
function errorCB(tx, err)
{
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB()
{
alert("success!");
}
function add()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
for more see link here
//show data from db
// Transaction success callback
function show()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(queryDB, errorCB);
}
// Query the database
function queryDB(tx)
{
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}
// Query the success callback
function querySuccess(tx, results)
{
var len = results.rows.length;
console.log("DEMO table: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " sname = " + results.rows.item(i).sname + " saddress = " + results.rows.item(i).saddress);
}
}
// Transaction error callback
function errorCB(err)
{
console.log("Error processing SQL: "+err.code);
}
Inside your code for save call
db.transaction(populateDB, errorCB, successCB)
The function will return to
function populateDB(tx) {
var rr=escape(JSON.stringify(onedata));//here onedata is data you want to save I use json data here.
tx.executeSql('CREATE TABLE IF NOT EXISTS LeadInfo (data)');
tx.executeSql('INSERT INTO LeadInfo (data) VALUES ("'+ rr +'")');
alert("Insert")
}
function errorCB(tx, err) {
//alert("Error processing SQL Insert: "+err);
}
function successCB() {
// alert("success!");
}
For retrieval you can use following:
function queryDB(tx) {
tx.executeSql('SELECT * FROM LeadInfo', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
var tablereport="";
if (results != null && results.rows != null) {
for (var i = 0; i < results.rows.length; i++) {
var row =unescape(results.rows.item(i).data);
var obj = JSON.parse(row);
tablereport+='<a href="#"><span style="font-size:18px; font-weight:400; padding:10px 0px 10px 0px;">'+JSON.stringify(obj.lead_name)+'</span><span style="padding: 10px 16px;width: 100px;float: right;margin-top: -33px;margin-right: -80px;font-size:14px"></span><br>';
tablereport+='</li>';
tablereport+='</li>';
}
}
}
function errorCB(err) {
alert("Error processing SQL Retrive: "+err.code);
}

Categories

Resources