Reputation: 1018
I am having a little bit of trouble... I am trying to get a lookup result as part of a web app, but struck-upon a little trouble.
I have a function that runs of a button click:
$(function() {
$('#bnt_fund_8y').click(function() {
console.log(dbCheck("study_mode"));
}
});
This dbCheck function goes away and check the local DB to see what study_mode is set, in the below function:
dbCheck = function(dbSearch) {
mydb.transaction(
function(transaction) {
transaction.executeSql('SELECT "'+dbSearch+'" FROM funding WHERE id = 1',[], function(transaction, results) {
var dbResult = results.rows.item(0).study_mode;
alert(dbResult);
return(dbResult);
}, errorHandler);
});
}
The alert display the correct variable, but he console log displays undefined. any help on this welcome...
Upvotes: 1
Views: 808
Reputation: 1073988
transaction
is an asynchronous call, so your function returns (without returning any value) before the callback you give transaction
occurs. The return
statement in your code isn't returning anything out of dbCheck
, but rather out of the callback function you've provided.
You'll need to change the function, and how you call it.
Function changes:
// add callback parameter --v
dbCheck = function(dbSearch, callback) {
mydb.transaction(
function(transaction) {
transaction.executeSql('SELECT "'+dbSearch+'" FROM funding WHERE id = 1',[], function(transaction, results) {
var dbResult = results.rows.item(0).study_mode;
alert(dbResult);
// Call the callback with the result
callback(dbResult);
}, errorHandler);
});
}
Calling it:
$(function() {
$('#bnt_fund_8y').click(function() {
dbCheck("study_mode", function(result) {
console.log(result);
});
}
});
Upvotes: 2
Reputation: 730
From what I can tell,
the function dbCheck isn't returning anything at all.
mydb.transactionis the function that is actually returning something.
As everyone else is pointing out, mydb.transactionis asynchronous.
You should just add
console.log(dbResult);
into the callback being passed into mydb.transaction
Upvotes: 0
Reputation: 700152
You can't return anything from the callback of an asynchronous call. Use a callback for the result also:
dbCheck = function(dbSearch, callback) {
mydb.transaction(
function(transaction) {
transaction.executeSql('SELECT "'+dbSearch+'" FROM funding WHERE id = 1',[], function(transaction, results) {
var dbResult = results.rows.item(0).study_mode;
callback(dbResult);
}, errorHandler);
});
});
};
Usage:
dbCheck("study_mode", function(value) {
console.log(value);
});
Upvotes: 0
Reputation: 664196
dbCheck = function(dbSearch) {
mydb.transaction(
...
);
}
does not return anything, so the value you get is undefined
. As transaction
seems to be an aynchronous call with callback functions, the only useful thing to return would be a promise for dbResult
.
Upvotes: 0