How do I return the number of rows of a table according to a search criteria in Web SQL? - html

I have created a database called todo with table name todo having fields like title,date etc. The table is empty right now.
I have defined a function which takes title as parameter and check whether table contains that title or not.
It should return the number of rows.
GetTitle function:
todo.webdb.GetTitle = function(title) {
var db = todo.webdb.db;
db.transaction(function(tx){
tx.executeSql("SELECT title FROM todo WHERE title=?", [title],
loadTitle,
todo.webdb.onError);
});
}
loadTitle Function:
function loadTitle(tx, rs) {
return rs.rows.length;
}
GetTitle Function is called:
row=todo.webdb.GetTitle("Hello");
alert(row);
I get alert 'undefined' it should return 0
I am confused right now how to resolve this issue.

I think the transactions are asynchronous, so you need to callback function to receive the value.
todo.webdb.GetTitle = function(title, callback) {
var db = todo.webdb.db;
db.transaction(function(tx){
tx.executeSql("SELECT title FROM todo WHERE title=?", [title],
(function loadTitle(tx, rs){
callback( rs.rows.length );
}),
todo.webdb.onError);
});
}
todo.webdb.GetTitle( "Hello", function(count){
alert( "count = " + count );
});
Here's an excellent tutorial for more information.
http://blog.darkcrimson.com/2010/05/local-databases/
Update
Don't make functions inside a loop for this main reason.
Both i and title are referencing a value created out of local scope.
So the last value of assigned to both i and title will be displayed.
for (i = 0; i < itemcount; i++) {
alert('i outside if:' + i);
var title = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
todo.webdb.GetTitle( title, function (count) {
if (!count) {
alert('i inside if:' + i);
alert( title );
}
});
}
Fix:
Generate a function that has the values locked in a closure.
var createTitleCallBack = function( i, title ){
return function (count) {
if (!count) {
alert('i inside if:' + i);
alert( title );
}
};
};
for (i = 0; i < itemcount; i++) {
alert('i outside if:' + i);
var title = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
todo.webdb.GetTitle( title, createTitleCallBack( i, title ) );
}

Related

Force localStorage event to fire in a different window

When the user clicks on a link it opens a page, adds some content to the local storage then the page that was just opened is supposed to listen for localStorage events. It doesn't seem to fire as I understand both windows must be opened at the same time for the storage event to fire. So I tried to invoke it manually like this:
//page containing the link to other window
$('.view-btn').click(function () {
var selectionName = $(this).parent().parent().find('td:first').text();
var key = "sel-view-1";
addToStorage(key, selectionName);
});
var addToStorage = function (key, value) {
defineKey(key, value);
var e = $.Event("storage");
e.originalEvent = {
key: key,
newValue: value
};
var windowRef = window.open("Create_a_selection", "_self");
$(windowRef).trigger(e);
};
var defineKey = function (key, value) {
if (localStorage.getItem(key) === null) {
localStorage.setItem(key, value);
} else {
var nr = parseInt(key.substring(key.lastIndexOf('-') + 1)) + 1;
key = 'sel-view-' + nr;
return defineKey(key, value);
}
}
//page that was just opened
$(window).bind('storage', onStorageEvent);
function onStorageEvent(storageEvent) {
console.log('yay');
if (storageEvent.originalEvent) {
var key = storageEvent.originalEvent.key;
var value = storageEvent.originalEvent.newValue;
if (key.indexOf("sel-view") > -1) {
$('#selection-name-label').html(value);
}
}
};
But this still doesn't catch the event... It does however catch it if the page is already opened so I'm wondering if this could have something to do with the page not being loaded yet perhaps?
Any help is appreciated.

Why can't my html5 class find my observable array contents?

Thanks in advance for any help. I have spent a couple of weeks scouring the web for some insight. I have been developing code for over 50 years but I am a fairly new JavaScript, HTML, knockout. From what I see, this will be great if I can figure out how to make it work. The example given below is only one of the many things I have tried. Please advise.
I have defined two variables as observables, one computed observable, and one observableArray in my view model. Within the document.ready function, I make an Ajax call which returns a json in object notation. ( I checked it in the debugger). When my HTML page displays the observables and computed observables show up properly. The
observable array generates an error (see below) and then displays data obtained from only the first row returned from Ajax. (two were returned).
How do I adjust my code so that all the rows in the Ajax data are shown in the displayed HTML?
Here is the error message that I get:
Uncaught ReferenceError: Unable to process binding "foreach: function (){return cartItems }"
Message: Unable to process binding "text: function (){return itemSubTotal() }"
Message: itemSubTotal is not defined (19:41:39:172 | error, javascript)
Here is my global data for the view model:
var cartDB = "";
var totalPrice = "100";
var cartItems = new Array;
Here is the view model:
var ViewModel =function (){
// direct items ==
this.cartDB = ko.observable(cartDB);
// array itesm
// this.cartItems = ko.observableArray(cartItems);
this.cartItems = ko.mapping.fromJS(cartItems);
//for (var n = 1;n++;n<cartItems.length){ this.cartItems.push(cartItem[n]);}
// computed items
this.totalPriceSv = ko.computed(function(){
return "Total Price*=" + centsToDollars(totalPrice);// todo fix
} ,this);//end totalSvPrice
};// end ViewModel
The data is obtained from the following routine which calls on Ajax.This routine is called once from within document.ready and obtains the expected data on the success callback.
function databaseCart(commandInput, cartDBInput, cartPidInput,logPhpInput) {
var postData = new Array();
postData[0] = commandInput;
postData[1] = cartDBInput;
postData[2] = cartPidInput;
postData[3] = logPhpInput; //debug log on php side
data = null; //for return values
$.ajax({
type: "GET",
url: 'ww_CartProcess.php', //the script to call to get data
data: {data: postData},
dataType: 'json',
success: function(data) {
cartItems = data;
debug = 0;
},
complete: function(data) {
ko.applyBindings(new ViewModel);
return TRUE;
},
error: function(x, e) {//this is the error function for ajax
var xErr = x;
var eErr = e;
ajaxErrorProcessing(xErr, eErr, "addToCart", postData);
}
});
}// end databasecart
Here is the HTML 5 snippet.
<div>
<h1 id="cartTitle">Cart Number: <span data-bind="text: cartDB"> </h1>
<div class ="boxCartItem" data-bind="foreach:cartItems" >
<div class ="boxItemTitle">
<h2 data-bind="text: title()"></h2>
</div><!--boxItemTitle-->
<div class ="cartItemBottom"></div>
</div ><!--class ="boxCartItem"-->
My thanks to the commenters. I still do not know how to add an element to all item rows in an observable array, but this problem was caused by not having the item listed defined. Clue> When multiple errors are presented it is sometimes ( and maybe always) good to work from the bottom up.
The problem can be better stated as : Given a 2 x 17 array (2 rows and 17 columns of independent vars)create an observableArray that contains 2 rows and 17 plus columns consisting of the 17 independent variables (can only be changed in the database or by limited user input) augmented with a large number of computed functions .
1.0 I created an orderModel which contained the ko.computed(functions() for each dependent variable.
function rowOrder(data) {
var self = this;
var model = ko.mapping.fromJS(data, {}, self);
model.imagePathSv = ko.computed(function() {
var category = self.category();
var imageName = self.imageName();
var sv ="";
var sv = "products\\" +category+"\\" + imageName;
return sv;
});//end model.imagePathSv
//original offer
model.origNumValidate = ko.computed(function() {
ans = self.origNum();
if (ans < 0 | ans > 1) {
alert("\
Only onw Original can be pruchased");
ans = 1;
}
self.origNum(ans);
return ans;
});//originalNumValidate
model.origNumLabel = ko.computed(function() {
var sv = "Original..." + centsToDollars(self.origCost());
return sv;
});//end model.origNumLabel
model.origMattedShow = ko.computed(function() {
if (self.origMattedCost() > 0) {
return true;
}
else {
return false;
}
});
model.origMattedLabel = ko.computed(function() {
var sv = "Matting...." + centsToDollars(self.origMattedCost());
return sv;
});
model.origFramedShow = ko.computed(function() {
if (self.origFramedCost() > 0) {
return true;
}
else {
return false;
}
});
model.origFramedLabel = ko.computed(function() {
var sv = "Framing...." + centsToDollars(self.origFramedCost());
return sv;
});
//reproductons offer
model.reproNumValidate = ko.computed(function() {
ans = self.reproNum();
self.reproNum(ans);
return ans;
});
model.reproNumLabel = ko.computed(function() {
var sv = "Reproductions." + centsToDollars(self.reproCost()) + " each";
return sv;
});//end model.reproNumLabel
model.reproMattedShow = ko.computed(function() {
if (self.reproMattedCost() > 0) {
return true;
}
else {
return false;
}
});
model.reproMatted = ko.observable(true);
model.reproMattedLabel = ko.computed(function() {
var sv ="Matting...." +centsToDollars(self.reproMattedCost());
return sv;
});
model.reproFramedShow = ko.computed(function(){
if(self.reproFramedCost()>0){return true;}
else {return false;}
});
model.reproFramed = ko.observable(true);
model.reproFramedLabel = ko.computed(function() {
var sv ="Framing...." +centsToDollars(self.reproFramedCost());
return sv;
});
//pricing subTotals
model.productsSubTotal = ko.computed(function() {
var ans =self.origNum() * self.origCost() + self.reproNum() * self.reproCost();
return ans;
});//end model.productsSubTotal
model.productsSubTotalSv = ko.computed(function() {
return "Products.." +centsToDollars(model.productsSubTotal());
return ans;
});//end model.productsSubTotal
model.mattingSubTotal = ko.computed(function() {
return self.origNum() * self.origMattedCost() + self.reproNum() * self.reproMattedCost();
});//end model.mattingSubTotal
model.mattingSubTotalSv = ko.computed(function() {
return "Matting...." +centsToDollars(model.mattingSubTotal());
});//end model.mattingSubTotal
model.framingSubTotal = ko.computed(function() {
return self.origNum() * self.origFramedCost() + self.reproNum() * self.reproFramedCost();
});//end model.framingSubTotal
model.framingSubTotalSv = ko.computed(function() {
return "Framing...." +centsToDollars(model.framingSubTotal());
});//end model.productsSubTotal
model.rowSubTotal = ko.computed(function() {
return model.productsSubTotal() +model.mattingSubTotal() + model.framingSubTotal();
});//end model.rowsSubTotal
model.rowSubTotalSv = ko.computed(function() {
return "Item Subtotal.." +centsToDollars(model.rowSubTotal());
});//end model.productsSubTotal
};// END rowOrder
2.0 I created a mapping variable as follows:
var mapping = {
create: function(options) {
return new rowOrder(options.data);
}
};
3,0 I created a View Model as follows:
function ViewModel() {
// direct items for whole page
var self = this;
this.cartId = ko.observable(cartDB);
this.cartIdSv = ko.computed(function() {
var sv = "Cart Number: "+ self.cartId();
return sv;
},this);//
this.totalPrice = ko.computed(function() {//to DO COMPUTE
var int = 10000;
return int;
},this);
this.totalPriceSv = ko.computed(function(){
return "Total Price*: " + centsToDollars(this.totalPrice());
},this);
// by row items
this.cartItems = ko.mapping.fromJS(cartItems, mapping);
}// end ViewModel
4.0 In the success call back from ajax :
success: function(data) {
cartItems = data;
ViewModel();
5.0 I put the ko.apply.bindings(new ViewModel) in the ajax complete callback.
The result was that my rather involved page came up as expected with the computed values initially set.
I am still working on how to update this page. I have not been able to get my code to recompute the computed variables when the user clicks or unclicks a checkbox.
I could not have done this without suggestions from the stackOverflow group. Thanks to you all for the posts that I found all over the google.

Windows 8 Javascript Promises

I have the following function:
function pickContacts() {
var output = "";
// Create the picker
var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
picker.commitButtonText = "Select";
var emailsPromise = new WinJS.Promise(function () {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
});
return emailsPromise;
};
This gets me a list of e-mail addresses from selected contacts. So next I want to use that; here's my code:
document.getElementById("findEmail").addEventListener("click", function () {
var emailAdd = document.getElementById("email");
pickContacts().done(function (emails) {
emailDets.value = emails;
});
});
But I'm not getting the return value from pickContacts (which I've determined is actually returned). I'm guessing that there's something wrong with the way I'm handling the returned promise, but I can't seem to debug it (trying to step into it just exits the function).
What am I doing wrong?
You don't need to create a new promise--just return the promise from pickMultipleContactsAsync.then. The promises spec says that the return value from .then is another promise that's fulfilled when your completed handler finishes, and the fulfillment value is the return value of the completed handler. So you can just do this:
return picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
The other way works, but just creates yet another promise that isn't needed, and makes your code a little more complex.
You'll have to pass the completed callback as a parameter of your promise function and then call it with the results you want to pass. Esseintially:
var emailsPromise = new WinJS.Promise(function () {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
});
becomes:
var emailsPromise = new WinJS.Promise(function (complete, error, progress) {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
complete(output);
} else {
complete("");
}
});
});

How can I do this asyn feature in nodejs

I have a code to do some calculation.
How can I write this code in an asyn way?
When query the database, seems we can not get the results synchronously.
So how to implement this kind of feature?
function main () {
var v = 0, k;
for (k in obj)
v += calc(obj[k].formula)
return v;
}
function calc (formula) {
var result = 0;
if (formula.type === 'SQL') {
var someSql = "select value from x = y"; // this SQL related to the formula;
client.query(someSql, function (err, rows) {
console.log(rows[0].value);
// *How can I get the value here?*
});
result = ? // *How can I return this value to the main function?*
}
else
result = formulaCalc(formula); // some other asyn code
return result;
}
Its not possible to return the result of an asynchronous function, it will just return in its own function scope.
Also this is not possible, the result will always be unchanged (null)
client.query(someSql, function (err, rows) {
result = rows[0].value;
});
return result;
Put a callback in the calc() function as second parameter and call that function in the client.query callback with the result
function main() {
calc(formula,function(rows) {
console.log(rows) // this is the result
});
}
function calc(formula,callback) {
client.query(query,function(err,rows) {
callback(rows);
});
}
Now if you want the main to return that result, you also have to put a callback parameter in the main and call that function like before.
I advice you to check out async its a great library to not have to deal with this kind of hassle
Here is a very crude way of implementing a loop to perform a calculation (emulating an asynchronous database call) by using events.
As Brmm alluded, once you go async you have to go async all the way. The code below is just a sample for you to get an idea of what the process in theory should look like. There are several libraries that make handling the sync process for asynch calls much cleaner that you would want to look into as well:
var events = require('events');
var eventEmitter = new events.EventEmitter();
var total = 0;
var count = 0;
var keys = [];
// Loop through the items
calculatePrice = function(keys) {
for (var i = 0; i < keys.length; i++) {
key = keys[i];
eventEmitter.emit('getPriceFromDb', {key: key, count: keys.length});
};
}
// Get the price for a single item (from a DB or whatever)
getPriceFromDb = function(data) {
console.log('fetching price for item: ' + data.key);
// mimic an async db call
setTimeout( function() {
price = data.key * 10;
eventEmitter.emit('aggregatePrice', {key: data.key, price: price, count: data.count});
}, 500);
}
// Agregate the price and figures out if we are done
aggregatePrice = function(data) {
count++;
total += data.price;
console.log('price $' + price + ' total so far $' + total);
var areWeDone = (count == data.count);
if (areWeDone) {
eventEmitter.emit('done', {key: data.key, total: total});
}
}
// We are done.
displayTotal = function(data) {
console.log('total $ ' + data.total);
}
// Wire up the events
eventEmitter.on('getPriceFromDb', getPriceFromDb);
eventEmitter.on('aggregatePrice', aggregatePrice);
eventEmitter.on('done', displayTotal);
// Kick of the calculate process over an array of keys
keys = [1, 2, 3]
calculatePrice(keys);

HTML5 Sequential execution

I have created a web storage for product details (productId, name, quantityonhand) and have populate records into it from the server. I have to validate whether the required quantity is available to accept the order.
The Product form has checkboxes (with name="product") for every product available in the web storage and a corresponding text input field to accept the quantity required.
The validation method is defined as follows.
function productValidation(){
for(i=0;i<document.Products.product.length;i++){
// checking whether the product has been checked / choosen
if (document.Products.product[i].checked==true){
var productId = document.Products.product[i].value;
var qty = document.Products.p[i].value;
var db = systemDB;
// validating the available quantity
db.transaction(
function(transaction){
transaction.executeSql('select * from product where productId=?;',
[productId],
function(transaction, results){
for (var j=0; j<results.rows.length; j++) {
var row = results.rows.item(j);
if (qty>row['qoh']){
alert(
row['productname']
+ ' is out of stock. We can serve you only '
+ row['qoh'] + ' quantities currently!');
document.Products.product[i].checked = false;
document.Products.p[i].value = 0;
}
}
});
}
);
}
}
return false;
}
When this code is executed, because of asynchronous nature of the db.transaction, the outer loop is getting executed and the validation is happening only for the last product choosen.
Help me to fix this. I want the execution happen sequentially.
Yuvi
Try chaining together calls in the callback function for db.transaction:
function productValidation(){
checkProductsSequential(document.Products.product, 0);
return false;
}
function checkProductsSequential(products, i)
{
if (i < products.length)
{
// checking whether the product has been checked / choosen
if (document.Products.product[i].checked==true){
var productId = document.Products.product[i].value;
var qty = document.Products.p[i].value;
var db = systemDB;
// validating the available quantity
db.transaction(
function(transaction){
transaction.executeSql('select * from product where productId=?;',
[productId],
function(transaction, results){
for (var j=0; j<results.rows.length; j++) {
var row = results.rows.item(j);
if (qty>row['qoh']){
alert(
row['productname']
+ ' is out of stock. We can serve you only '
+ row['qoh'] + ' quantities currently!');
document.Products.product[i].checked = false;
document.Products.p[i].value = 0;
}
}
checkProductsSequential(products, i + 1)
});
}
);
}
else
{
checkProductsSequential(products, i + 1)
}
}
}