Web db - getting the data back - javascript

Here is the code
onError = function(tx, e) {
alert('Something unexpected happened: ' + e.message );
}
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
webdb.transaction(function(tx) {
tx.executeSql('SELECT * FROM colours',
[],
function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
},
onError);
});
/**
* the array looks like [[1,'red'],[2,'white'],[3,'black'] ...]
*/
var ColourStore = new Ext.data.ArrayStore({fields: ['key', 'val'],
data: colourArray});
The table "colours" contain colour name and hash code. And it was suppose to be use by a ExtJS Ext.data.ArrayStore then populate other drop downs on a massive form.
My problem is - I couldn't get the data back as an array. The variable "colourArray" is empty ... I know I hit some javascript closure , loop problem ... but just couldn't figure out how to get that inner loop value back. Try a lot of return -> return -> return function and more return. None of them works.

executeSQL is asynchronous. You need to create ColourStore in the function(tx,rs) callback function. If you need the data available globally, you can't init your app until executeSQL calls the callback function. Example:
Ext.onReady( function() {
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
var ColourStore;
webdb.transaction( function(tx) {
tx.executeSql('SELECT * FROM colours',
[], function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
//INIT YOUR APP HERE IN ORDER TO HAVE ACCESS TO colourArray values
ColourStore = new Ext....
YourApp.init();
},
onError);
});
}, this);

Related

nested javascript queries in parse

I have the code below. Basically I have 3 nested parse queries. One is getting a number of "followers" and for each follower I am getting a number of "ideas" and for each idea I would like to get that idea creator's name (a user in the user table).
The first two nested queries work but then when i try to get the name of the user (the creator of the idea), that last nested query DOES NOT execute in order. That query is skipped, and then it is executed later in the code. Why is this happening please?
var iMax = 20;
var jMax = 10;
var IdeaList = new Array();
var IdeaListCounter = 0;
var myuser = Parse.User.current();
var Followers = new Parse.Query("Followers");
Followers.equalTo("Source_User",{__type: "Pointer",className: "_User",objectId: myuser.id});
Followers.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var Ideas = new Parse.Query("Ideas");
Ideas.equalTo("objectId_User", {__type: "Pointer",className: "_User",objectId: object.get('Destination_User').id});
Ideas.find({
success: function(results2) {
for (i=0;i<iMax;i++) {
IdeaList[i]=new Array();
for (j=0;j<jMax;j++) {
IdeaList[i][j]=0;
}
}
for (var j = 0; j < results2.length; j++) {
var object2 = results2[j];
var ideausername2 = "";
IdeaListCounter++;
var ideausername = new Parse.Query("User");
ideausername.equalTo("objectId",object2.get('objectId_User').id);
ideausername.first({
success: function(ideausernameresult) {
ideausername2 = ideausernameresult.get("name");
}
});
IdeaList[IdeaListCounter,0] = object2.get('objectId_User').id + " " + ideausername2; //sourceuser
IdeaList[IdeaListCounter,1] = object2.get('IdeaText'); //text
IdeaList[IdeaListCounter,2] = object2.get('IdeaImage'); //image
IdeaList[IdeaListCounter,3] = object2.get('IdeaLikes'); //likes
IdeaList[IdeaListCounter,4] = object2.get('IdeaReport'); //reports
Your nested query is asynchronous.
Check out the answer at the following for guidance:
Nested queries using javascript in cloud code (Parse.com)

Retrieving Data from existing database using webSQL?

i'm trying to retrieve the data from the database for web application using webSQL ,but i'm unable to get the data from database. I'm very new to this. I tried like this
var DB_NAME = "database";
var DB_VERSION = "";
var DB_TITLE = "";
var DB_BYTES = 50 * 1024 * 1024;
var db = openDatabase(DB_NAME, DB_VERSION, DB_TITLE, DB_BYTES);
//Retrieve Rows from Table
db.transaction(
function(tx) {
tx.executeSql("SELECT * FROM Data;",
[],
function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).text);
}
});
});
Thanks in Advance.
This is how i have done.. and this is working for me.
// global variables
var db;
var shortName = 'Books';
var version = '1.0';
var displayName = 'BooksDB';
var maxSize = 200000;//65535;
function ListDBValues() {
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
// this line tries to open the database base locally on the device if it does not exist, it will create it and return a database object stored in variable db
db = openDatabase(shortName, version, displayName,maxSize);
// this line clears out any content in the #lbUsers element on the page so that the next few lines will show updated content and not just keep repeating lines
$('#lbUsers').html('');
// this next section will select all the content from the User table and then go through it row by row appending the UserId FirstName LastName to the #lbUsers element on the page
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM books;', [], function(transaction, result) { if (result != null && result.rows != null) { for (var i = 0; i < result.rows.length; i++) { var row = result.rows.item(i); $('#lbUsers').append('<br>' + row.book_title + '. ' + row.book_isbn+ ' ' + row.book_price); } } },errorHandler); },errorHandler,nullHandler);
return;
alert('in list end');
}
// this is called when a successful transaction happens
function successCallBack() {
alert("DEBUGGING: success");
}
function nullHandler(){
alert('null handler');
};

After I call an array returned from function, it give me "undefined"

I call the facebook fql to get all members of a group. If i check allmembers in the first function, it works just fine, but when i call it in the second one, in returns "undefined".
function getAllMembers(groupid){
var allmembers = new Array();
var content = document.getElementById('content-text');
FB.api({
method: 'fql.query',
query: 'select uid from group_member where gid =' + groupid
},
function(resp){
for (var i=0, l= resp.length; i<l; i++)
{
allmembers[i] = resp[i].uid;
}
return allmembers;
}
)
}
function retrieveMessages(groupid){
var allmembers;
allmembers = getAllMembers(groupid);
console.log(allmembers);
}
I don't understand where's the mistake.
It looks like getAllMembers() is making a asynchronous function call using FB API, which means that the getAllMembers() returns before the FB call is completed.
You need to use a callback function, to solve this problem as given below
function getAllMembers(groupid, callback){
var content = document.getElementById('content-text');
FB.api({
method: 'fql.query',
query: 'select uid from group_member where gid =' + groupid
}, function(resp){
var allmembers = new Array();
for (var i=0, l= resp.length; i<l; i++)
{
allmembers.push( resp[i].uid);
}
callback(allmembers)
})
}
function retrieveMessages(groupid){
getAllMembers(groupid, function(allmembers){
console.log(allmembers);
});
}
At a guess the call is asynchronous - which means that getAllMembers returns before your success function (function(resp){}) executes...
Try moving the console.log inside your function(resp)...
var allmembers = new Array();
function getAllMembers(groupid){
var allmembers = new Array();
var content = document.getElementById('content-text');
FB.api({
method: 'fql.query',
query: 'select uid from group_member where gid =' + groupid
},
function(resp){
for (var i=0, l= resp.length; i<l; i++)
{
allmembers[i] = resp[i].uid;
}
console.log(allmembers);
}
);
}
function retrieveMessages(groupid){
getAllMembers(groupid);
}

Is the unnecessary to loop through the result of an executeSql command?

There's a lot of code here, but the question has to do with the for loop at the bottom.
var dbo = openDatabase('xxx','1.0','myDatabase', 1048576);
var DropTableDeferred = new $.Deferred();
var CreateTableDeferred = new $.Deferred();
var InsertDeferred = new $.Deferred();
var SelectDeferred = new $.Deferred();
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'drop table myTable;'
,[]
,DropTableDeferred.resolve()
);
});
DropTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'CREATE TABLE IF NOT EXISTS myTable'
+ '(xxxID Integer NOT NULL PRIMARY KEY'
+ ',xxxName Varchar(128)'
+ ');'
,[]
,CreateTableDeferred.resolve()
);
});
});
CreateTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(1,'A')");
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(2,'B')");
myTrans.executeSql(
"INSERT INTO myTable(xxxID,xxxName) VALUES(3,'C')",
[],
InsertDeferred.resolve()
);
});
});
InsertDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'SELECT * FROM myTable',
[],
function(tx, result) {
SelectDeferred.resolve(result);
}
);
});
});
SelectDeferred.done(function(result) {
var X = $('#result-template').html();
var template = Handlebars.compile(X);
var data = [];
for(var i=0;i < result.rows.length; i++) {
data.push(result.rows.item(i));
}
$('ul').append(template(data));
});
Q: Do I need to build a data array in order to call template(data), or can I pass the result variable directly?
And by 'result variable', what I mean is: result.rows, or result.rows.item, or some other combination.
Yes the value has passed directly in my html&javascript only project. In the code below, I get the results of the Sql and filling a dropdown box's options.
function fillLectureFromDB(tx) {
tx.executeSql('SELECT * FROM LECTURE', [], successFill, errorFill);
}
function successFill(tx, results) {
var len = results.rows.length;
for (var i=0; i<len; i++){
var elOptNew = document.createElement('option');
elOptNew.text = results.rows.item(i).code;
elOptNew.value = results.rows.item(i).code;
var elSel = document.getElementById('slExCode');
elSel.add(elOptNew, null);
}
}
IMHO you can, but to tell you the truth, it would've taken less time for you to try it out then to post the question. Just try:
$('ul').append(template(result.rows));

My websql transaction won't execute

I have a mobile app in HTML5 that is using the websql database. I have a data.js file with a bunch of functions for doing various CRUD jobs with the database. I've never had this problem until I got to wiring this function. Basically the app is for creating quotes for tradesmen and the function I'm writing is getting the quote and quote lines, converting them into and array of JSON objects and ajaxing them to a web app.
For some reason my db.transaction's are not being executed. Can you help me figure out why? The db exists as other functions are calling this exact SQL. But it works for them and not this one:
function syncQuote(){
var quote_id = localStorage["quote_id"];
var header = new Array(); // holds id, created, appointment_id
db = openDatabase("Quote", "0.1", "A collection of quotes.", 200000);
if(!db){
console.log('Failed to connect to database.');
}
console.log('Getting quote header data.');
db.transaction(
function(tx) {
tx.executeSql("SELECT * FROM quote_header WHERE id = ?", [quote_id],
function(tx, results) {
var len = results.rows.length;
for(var i=0; i< len; i++){
alert('booyah!');
header['quote_id'] = results.rows.item(i).id;
header['appointment_id'] = results.rows.item(i).appointment_id;
header['created'] = results.rows.item(i).created;
}
});
},
function(tx, error){
console.log(error.message);
}
);
// now get all quote lines for this quote
var lines = new Array();
console.log('getting quote lines');
db.transaction(
function(tx) {
tx.executeSql("SELECT DISTINCT areas.label as area, features.label as feature, products.label as product, hours, price, colour FROM quote_line JOIN areas ON quote_line.area_id = areas.area_id JOIN features ON quote_line.feature_id = features.feature_id JOIN products ON quote_line.product_id = products.product_id WHERE quote_line.quote_id = ?", [quote_id],
function(tx, results) {
len = results.rows.length;
for(var i=0; i< len; i++){
var area= results.rows.item(i).area;
var feature= results.rows.item(i).feature;
var product= results.rows.item(i).product;
var hours= results.rows.item(i).hours;
var price= results.rows.item(i).price;
var colour= results.rows.item(i).colour;
lines[i] = new Array(6);
lines[i][0] = area;
lines[i][1] = feature;
lines[i][2] = product;
lines[i][3] = hours;
lines[i][4] = price;
lines[i][5] = colour;
}
},
function(tx, error){
console.log(error.message);
}
);
}
);
var data = new Array(2);
data[0] = JSON.stringify(header);
data[1] = JSON.stringify(lines);
alert(data[0]);
alert(data[1]);
// post data to web app
var url = "http://*****.com/import_quote";
$.ajax({
type: 'POST',
url: url,
data: data,
success: quote_sync_success,
dataType: 'JSON'
});
}
I have both success and fail callbacks but neither is responding.
Also this is the first time I'm posting JSON from a JS app so feel free to comment.
Thanks,
Billy
Copy this edited codes and see if it works
function syncQuote(){
var quote_id = localStorage["quote_id"];
var header = new Array(); // holds id, created, appointment_id
db = openDatabase("Quote", "0.1", "A collection of quotes.", 200000);
if(!db){
console.log('Failed to connect to database.');
}
console.log('Getting quote header data.');
db.transaction(
function(tx) {
// CORRECTION 1: THE ? IS MEANT TO BE IN A BRACKET
tx.executeSql("SELECT * FROM quote_header WHERE id = (?)", [quote_id],
function(tx, results) {
var len = results.rows.length;
for(var i=0; i< len; i++){
alert('booyah!');
header['quote_id'] = results.rows.item(i).id;
header['appointment_id'] = results.rows.item(i).appointment_id;
header['created'] = results.rows.item(i).created;
}
});
},
function(tx, error){
console.log(error.message);
},
//CORRECTION 2
//THERE IS MEANT TO BE A SUCCESS CALL BACK FUNCTION HERE
function(){
console.log( 'Query Completed' )
}
);
// now get all quote lines for this quote
var lines = new Array();
console.log('getting quote lines');
db.transaction(
function(tx) {
// CORRECTION 3: WRONG CALL METHOD AND NONE-USE OF BRACKETS and QOUTES
tx.executeSql("SELECT DISTINCT areas.label as area, features.label as feature, products.label as product, hours, price, colour FROM quote_line JOIN areas ON quote_line.area_id = 'areas.area_id' JOIN features ON quote_line.feature_id = 'features.feature_id' JOIN products ON quote_line.product_id = 'products.product_id' WHERE quote_line.quote_id = (?)", [quote_id],
function(tx, results) {
len = results.rows.length;
for(var i=0; i< len; i++){
var area= results.rows.item(i).area;
var feature= results.rows.item(i).feature;
var product= results.rows.item(i).product;
var hours= results.rows.item(i).hours;
var price= results.rows.item(i).price;
var colour= results.rows.item(i).colour;
lines[i] = new Array(6);
lines[i][0] = area;
lines[i][1] = feature;
lines[i][2] = product;
lines[i][3] = hours;
lines[i][4] = price;
lines[i][5] = colour;
}
},
function(tx, error){
console.log(error.message);
}
);
}
);
var data = new Array(2);
data[0] = JSON.stringify(header);
data[1] = JSON.stringify(lines);
alert(data[0]);
alert(data[1]);
// post data to web app
var url = "http://*****.com/import_quote";
$.ajax({
type: 'POST',
url: url,
data: data,
success: quote_sync_success,
dataType: 'JSON'
});
}
have you tried throwing console.log()'s in at the start of your success callbacks? if len is 0 in those, you wouldn't get any output from them as is

Categories