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

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

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.

Return executeSQL function

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
}

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

JavaScript scope issue

I have the following piece of javascript but for some scoping reason the "names" that is returned from myfunc is empty.
var myfunc = function(client, id) {
var names = new Array();
client.query(
'SELECT stuff FROM mytable WHERE id="'+id+'"',
(function selectCb(err, results, fields) {
if (err) {
throw err;
}
for (result in results) {
// This prints fine
console.log(results[result].name);
names[result] = results[result].name;
}
client.end();
})
);
// The following returns empty
return names;
}
console.log(myfunc(1,2));
How can I make it break out of scope?
It's empty because the call to your "query" function is asynchronous. The function you pass into it won't be run until the results are available. Therefore, your "myfunc" function returns immediately, long before that callback function is invoked.
Using Javascript in a browser, you have to think in those terms. Instead of expecting your "names" to be ready immediately, change "myfunc" so that you pass it a callback function to be invoked when the names are actually available:
var myfunc = function(client, id, whenFinished) {
var names = new Array();
client.query(
'SELECT stuff FROM mytable WHERE id="'+id+'"',
(function selectCb(err, results, fields) {
if (err) {
throw err;
}
for (result in results) {
// This prints fine
console.log(results[result].name);
names[result] = results[result].name;
}
client.end();
if (whenFinished) whenFinished(names); // callback
})
);
};
Now when you call your function, instead of expecting the "names" as a return value, you'll pass in another function that will act on the list of names:
myfunc(1, 2, function(names) { console.log(names); });
If client.query(...) is asynchronous, then the selectCb function would not have run and names would not have changed by the time myfunc returns. You need to redesign myfunc to return names asynchronously (by, for example, accepting a function parameter which it calls at the end of selectCb).
var names = new Array();
var myfunc = function(client, id) {
client.query(
'SELECT stuff FROM mytable WHERE id="'+id+'"',function selectCb(err, results, fields)
{
if (err) {
throw err;
}
for (result in results) {
// This prints fine
console.log(results[result].name);
names[result] = results[result].name;
}
client.end();
}
);
// The following returns empty
return names;
}
console.log(myfunc(1,2));
try making names global

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