Return executeSQL function - javascript

I'm trying to return the results of a SQL query using SQLite.
The query works fine and I can output the results inside the executeSql function. But when I try to reach the array from my main function (returnSQLArray) it is undefined.
How do I solve this problem?
I'm calling returnSQLArray inside another function where I need the results from the query.
Code:
function returnSQLArray(str)
{
var db = window.openDatabase("Database", "1.0", "Name", 200000);
var result = [];
db.transaction(
function (tx, results) {
tx.executeSql(str, [], function(tx, rs) {
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
id: row['id']
}
}
console.log(result[0].id); //Returns the id
});
}
);
console.log(result[0].id); //Undefined
}
Thank you

It's an async issue. db.transaction takes a callback which executes after the sqlite transaction finishes. Your console.log() statement shown at the end of your method is actually happening before result has been populated.
EDIT ADDITION:
functions getPersons() {
returnSQLArray('SELECT * FROM PERSONS', processPersonsResponse);
}
function returnSQLArray(str, callback) {
...
tx.executeSql(str, [], function(tx, rs) { callback(result); });
}
function processPersonsResponse(response) {
//do work with response
}

Related

get return value from sql request

I'm currently working on a little app using phonegap and sqllite.
Filling the database works fine; but I need a function which returns me a html-string (for a id).
I have this little snippet from the internet which I "improved" for my purpose, but it doesn't work like expected :(
function getPriceFromDatabase(id) {
var result = [];
// Query the database
//
function queryDB(tx) {
tx.executeSql('SELECT * FROM PRICEFTS WHERE pid MATCH ' + id, [], querySuccess, errorCB1);
}
// Query the success callback
//
function querySuccess(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
result.push('<span class="'+results.rows.item(i).priceart+'">'+results.rows.item(i).price+'</span>');
}
}
// Transaction error callback
//
function errorCB1(err) {
console.log("Error SQL: " + err.code);
}
// Transaction success callback
//
var db = window.openDatabase("sucheDB", "1.0", "Suche DB", 52428800);
db.transaction(queryDB, errorCB1);
return result.join('');
}
Here is my sample event:
$("#price_button").click(function () {
var p = getPriceFromDatabase(88361);
console.log(p);
$('#price').html(p);
})
(I get always 'undefined' as result)
can someone help?
thanks! :)
You should provide the on-success callback to the db.transaction call, like this:
db.transaction(queryDB, errorCB1, querySuccess);
Also this function is probably async, so your return is executed before the transaction could finish.

Web SQL transaction does not execute properly in javascript function

I have JavaScript function that returns array of selected values from my local database.
var dataBase = {
select : selectFunction
}
var db = openDatabase(..);
var data=[ ];
function selectFunction() {
db.transaction(function (t) {
t.executeSql("SELECT * FROM Table", [], function (t, results) {
for (i = 0; i < results.rows.length; i++) {
data.push(results.rows.item(i));
}
});
});
return data;//return "stackoverflow" //works fine
}
I want to do something like this
var getSelect = dataBase.select();
alert(getSelect);
If I return string like "stackoverflow", this will work fine
alert result: stackoverflow
But if I try to return the 'data', the function returns undefined
I noticed that db.transaction is executing after the return statement, and I don't know how to fix this.
When returning results from an asynchronous function, you must use a callback, as the function will return before the actual operation has completed. You can rewrite your function like so:
function selectFunction(callback) {
db.transaction(function (t) {
t.executeSql("SELECT * FROM Table", [], function (t, results) {
for (i = 0; i < results.rows.length; i++) {
data.push(results.rows.item(i));
}
callback(data);
});
});
}
And then call it, passing a callback:
dataBase.select(function(data){
var getSelect = data
alert(getSelect);
});

how to pass arguments to PhoneGap database transaction function

I have a working PhoneGap database transaction where I am able to run a sql query and process the results. However, in an effort to make it reusable, I need to be abe to pass arguments to the querying function. There should a better way than declaring global variables and accessing them/resetting in the query function. Appreciate any help in converting this:
//update images function
function updateGalleryCovers() {
var db = window.openDatabase("test db", "1.0", "Cordova DB", 200000);
db.transaction(queryDB_u_g, errorCB);
}
//Query the database
function queryDB_u_g(tx) {
var query = 'SELECT cover_img, objectId FROM USER_GALLERY WHERE userId="'+getUserId()+'"';
tx.executeSql(query, [], querySuccess_u_g, errorCB);
}
//Query success callback
function querySuccess_u_g(tx, results) {
var len = results.rows.length;
for (var i=0; i<len; i++){
// process results
}
}
to something like this:
//update images function
function updateGalleryCovers(userid) {
var db = window.openDatabase("test db", "1.0", "Cordova DB", 200000);
db.transaction(queryDB_u_g, userid, errorCB);
}
//Query the database
function queryDB_u_g(tx, userid) {
var query = 'SELECT cover_img, objectId FROM USER_GALLERY WHERE userId="'+userid+'"';
tx.executeSql(query, [], querySuccess_u_g, errorCB);
}
//Query success callback
function querySuccess_u_g(tx, results) {
var len = results.rows.length;
for (var i=0; i<len; i++){
// process results
}
}
Thanks!
The transaction functions are offered by sqlite and not phonegap. Its true that you can't pass extra variables to the functions because of the method signature sqlite accepts.
But here's a work around for the same:
db_conn.transaction( function(tx){ your_function(tx, parameter1, parameter2) }, ErrorCallBack );
Here you are passing a dummy function to the transaction success callback and taking the transaction object along with it.
Hope that helps

How to store websql .executeSql results in a global variable?

How can access the results of a
tx.executeSql('select query for a table',[],sucessCB);
function sucessCB(tx, results){ //<--- this results param
console.log(results.row.item(0).name);
}
I tried something like
function(){
var tab = [];
tx.executeSql('select query for a table',[],sucessCB);
function sucessCB(tx, results){ //<--- this results param
console.log(results.row.item(0).name);
for(i=0;i<results.length;i++){
tab.push(results.row.item(i))
}
}
console.log(tab); //<--- this returns always null
}
how can access the variable outside the callback function or is there a way to store a sql results in variable directly. Is there a way to send variable into a callback function again in the
tx.executeSql('another select query',[],function(tx, results, tab ){ // <-- this inside sucessCB
console.log(tab);
});
In all the scenario the variable is null. Is there a another way to do this. Any suggestion would be helpful thanks.
You use callback as follow:
var querySql = function(sql, callback) {
tx.executeSql(sql,[],sucessCB);
function sucessCB(tx, results){ //<--- this results param
var tab = [];
for(i=0;i<results.length;i++){
tab.push(results.row.item(i))
}
callback(tab);
}
}
querySql('select query for a table', function(result) {
console.log(result);
}
However this kind of problem is better solved by using Deferred concept.
var querySql = function(sql) {
var df = $.Deferred();
tx.executeSql(sql,[],sucessCB, errCB);
function sucessCB(tx, results){ //<--- this results param
var tab = [];
for(i=0;i<results.length;i++){
tab.push(results.row.item(i))
}
df.resolve(tab);
}
function errCB(tx, e) {
df.reject(e);
}
}
querySql('select query for a table').done(function(result) {
console.log(result);
}

Capture value from nested function in JavaScript

I have the following code snippet :
function getCheckListTaskWithId(id){
var tempTask = db.readTransaction(function (tx) {
tx.executeSql('SELECT * FROM checklisttasks where id=? ', [id], function (tx, results) {
var len = results.rows.length;
if(len>0){
var task=results.rows.item(0);
var temp= new CheckListTask(task.id,task.crud,task.name,task.status);
alert(temp);
}
});
});
}
the function that I pass to the tx.execute method is a call back function. Now I wan to return temp var present in callback function, from getCheckListTaskWithId function.
How Do I do this?
I am assuming that the executions of db.readTransaction and tx.executeSql are asynchronous. So you cannot return the result from them, as you don't know when they'll finish. The solution is use an asynchronous callback yourself. Make the getCheckListTaskWithId take a callback function as an argument and call it when result it available.
function getCheckListTaskWithId(id, callback) {
var tempTask = db.readTransaction(function (tx) {
tx.executeSql('SELECT * FROM checklisttasks where id=? ', [id], function (tx, results) {
var len = results.rows.length;
if(len > 0) {
var task=results.rows.item(0);
var temp= new CheckListTask(task.id,task.crud,task.name,task.status);
alert(temp);
callback(temp);
}
});
});
}
Rewrite tx.executeSql so it gets the return value of the callback and returns it.
This assumes that tx.executeSql doesn't perform any Ajax. Ajax is Asynchronous, so an HTTP request is made, execution continues as normal and another function is run when the request comes back. In this case it is far too late to return a value to the earlier function and anything that needs to be done with the data can only be done by the callback.

Categories

Resources