PhoneGap jquerymobile SQL dynamic link - sql

I am building a PhoneGap iOS App with the help of the jquery-mobile framework. I have a primary jquery-mobile autodivided list, populated by an SQL database. This autodivided list work as expected. When clicking on one link of this dynamic list, a dynamic page is supposed to fire up, containing some extra details included in the same SQL database. However, when the database doesn't load the page details.
I successfully made this work outside jquerymobile framework, with a few script changes. But I really need the autodividers function coming from jquerymobile.
First I assumed that this dynamic page was outside the DOM, but adding the following function at mobileinit() doesn't solve my SQL loading issue:
$( 'fooddetails.html?id' ).live( 'pagebeforecreate',function(event, ui){
alert( 'This page was just inserted into the dom!' );
});
Below is a complete script for my database & the dynamic URL to fire the extra details page:
var db;
var dbCreated = false;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = window.openDatabase("FoodDirectoryDB", "1.0", "PhoneGap", 200000);
if (dbCreated)
db.transaction(getAlimentaries, transaction_error);
else
db.transaction(populateDB, transaction_error, populateDB_success);
}
function transaction_error(tx, error) {
$('#busy').hide();
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
db.transaction(getAlimentaries, transaction_error);
}
function getAlimentaries(tx) {
var sql = "select e.id, e.foodName, e.groupfoodName, e.quantity, e.picture, count(r.id) reportCount " +
"from food e left join food r on r.managerId = e.id " +
"group by e.id order by e.foodName ";
tx.executeSql(sql, [], getAlimentaries_success);
}
function getAlimentaries_success(tx, results) {
$('#busy').hide();
$('#foodList li').remove();
var len = results.rows.length;
for (var i=0; i<len; i++) {
var food = results.rows.item(i);
console.log(food.foodName);
$('#foodList').append('<li><a href="fooddetails.html?id=' + food.id + '">' +
'<img src="pics/' + food.picture + '" class="arrow-r"/>' +
'<p class="line1">' + food.foodName + '</p>' +
'</a></li>');
$( 'employeedetails.html?id' ).live( 'pageshow',function(event, ui){
alert( 'This page was just inserted into the dom!' );
});
}
$('#foodList').listview('refresh');
db = null;
}
function populateDB(tx) {
$('#busy').show();
tx.executeSql('DROP TABLE IF EXISTS food');
var sql =
"CREATE TABLE IF NOT EXISTS food ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"foodName VARCHAR(50), " +
"groupfoodName VARCHAR(50), " +
"quantity VARCHAR(50), " +
"portion VARCHAR(50), " +
"managerId INTEGER, " +
"glucides VARCHAR(30), " +
"picture VARCHAR(200))";
tx.executeSql(sql);
tx.executeSql("INSERT INTO food (id,foodName,groupfoodName,managerId,quantity,portion,glucides,picture) VALUES (1,'Abricot','Fruits frais et fruits secs',1,'1 abricot','65g','5','fruits_legumes.png')");
tx.executeSql("INSERT INTO food (id,foodName,groupfoodName,managerId,quantity,portion,glucides,picture) VALUES (2,'Abricots secs','Fruits frais et fruits secs',1,'4 abricots secs','80g','30','fruits_legumes.png')");
I was also trying to add data-ajax="false" rel"external" to this dynamic link, but this doesn't change unfortunately and I read that these attributes in a dynamic link are not authorized:
$('#foodList').append('<li><a href="fooddetails.html?id=' + food.id + '">' +
Below is the script of the details dynamic page that doesn't load correctly:
var id = getUrlVars()["id"];
var db;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("opening database");
db = window.openDatabase("FoodDirectoryDB", "1.0", "PhoneGap", 200000);
console.log("database opened");
db.transaction(getAlimentary, transaction_error);
}
function transaction_error(tx, error) {
$('#busy').hide();
alert("Database Error: " + error);
}
function getAlimentary(tx) {
$('#busy').show();
var sql = "select e.id, e.foodName, e.groupfoodName, e.managerId, e.quantity, e.portion, e.glucides, " +
"e.picture, m.foodName managerFirstName, m.groupfoodName managerLastName, count(r.id) reportCount " +
"from food e left join food r on r.managerId = e.id left join food m on e.managerId = m.id " +
"where e.id=:id group by e.groupfoodName order by e.groupfoodName, e.foodName";
tx.executeSql(sql, [id], getAlimentary_success);
}
function getAlimentary_success(tx, results) {
$('#busy').hide();
$('#foodList li').remove();
var food = results.rows.item(0);
$('#foodPic').attr('src', 'pics/' + food.picture);
$('#foodName').text(food.foodName);
$('#foodgroupName').text(food.groupfoodName);
$('#foodQuantity').text(food.quantity);
$('#foodPortion').text(food.portion);
console.log(food.glucides);
if (food.glucides) {
$('#actionList').append('<li><a href="tel:' + food.glucides + '"><p class="line1">Teneur en Glucides</p>' +
'<p class="line2">' + food.glucides + '</p><img src="img/food.png" class="action-icon"/></a></li>');
}
$('#foodList').listview('refresh');
db = null;
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}

Related

Cannot pass price into Stripe Checkout nodejs

I am using the embedded nodejs / javascript code for stripe checkout on my ecommerce website. However, I am trying to pass the name of the product(s) the customer will add to their cart, and the price as well, so I can display the items and prices on Stripe Checkout page.
I ran into the issue after making a connection to DB2, I cannot get the price of each item to be passed into the stripe checkout session. I think it may have to do with async, but even if it is, im not sure how to fix. I am also receiving the error: "(node:45673)UnhandledPromiseRejectionWarning: Error: Invalid integer: NaN"
(excuse the messy code. also some variables are not in use, just ignore)
app.post('/create-checkout-session', (req, res) => {
var amount = stringify(req.body)
console.log(req.body.sessionID)
var userId = req.body.sessionID
console.log("email: " + req.body.customer_email)
var email = req.body.customer_email;
var deliveryTotal = req.body.totalWithDelivery;
var totalVal = amount.split("=");
var totalPrice = parseFloat(totalVal[1]);
//console.log("TOTAL PRICE: " + totalPrice);
var finalPrice = parseFloat(Math.round(totalPrice * 100) / 100);
var finalTotal = parseFloat(Math.round(totalPrice * 100) / 100) + parseFloat(Math.round(deliveryTotal));
console.log("final total: " + finalTotal);
var itemName = ""
var itemPrice = ""
var totalNewPriceTest = ""
//query to database
var productsStripe = "select * from " + userId
console.log(userId)
console.log("query to db for displaying cart on stripe page")
ibmdb.open("DATABASE=BLUDB;HOSTNAME=;PORT=50000;PROTOCOL=TCPIP;UID="";PWD="";", function (err,conn) {
if (err) return console.log(err);
conn.query(productsStripe, function (err, rows) {
if (err) {
console.log(err)
}
console.log(rows)
for(var i = 0; i < rows.length; i++) {
itemName = rows[i]['ITEM']
itemPrice = rows[i]['PRICE']
totalNewPriceTest = parseFloat(rows[i]['PRICE'])
console.log("item name : " + itemName + " " + itemPrice )
totalNewPriceTest = parseFloat(totalNewPriceTest);
console.log("final overall prcie: " + (totalNewPriceTest))
}
console.log("inside productsStripe function.")
console.log("overall prcie: " + totalNewPriceTest)
})
})
totalNewPriceTest = parseFloat(totalNewPriceTest)
var grandTotal = totalNewPriceTest;
var finalGrandTotal = parseFloat(grandTotal)
console.log(parseFloat(finalGrandTotal))
//stripe
const session = stripe.checkout.sessions.create({
shipping_address_collection: {
allowed_countries: ['CA'],
},
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'CAD',
product_data: {
name: itemName,
},
unit_amount: finalGrandTotal,
//finalTotal * 100
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'localhost:1001/successPg',
cancel_url: 'localhost:1001/catalogue',
customer_email: email,
});
console.log(session)
res.json({ id: session.id });
//console.log("customer id" + customer.id)
console.log("totalNewPriceTest " + totalNewPriceTest)
});
can anyone help? thank you in advance, and sorry for the terribly written code :(
You have to write following lines inside query callback :-
totalNewPriceTest = parseFloat(totalNewPriceTest)
var grandTotal = totalNewPriceTest;
var finalGrandTotal = parseFloat(grandTotal)
console.log(parseFloat(finalGrandTotal))
And for error check before parsing the data to int or float like
if(!isNAN(field))
value = parseFloat(field);
I did follow what you said, no errors, however it still doesn't reach the stripe checkout page... it logs in the console: Promise { }. i did research this and it says this has to once again do with async. not sure how to fix, read something about .then may work as well?
As you have guessed, it's a classic concurrency issue, first of all, this complete guide from MDN explains asynchronous javascript very well.
To briefly answer your case, you will need to continue executing stripe code in the query block. Why? Because you need to wait for the DB connection to open followed by a query execution, which both are asynchronous.
When you bypass those blocks, you're basically telling javascript to execute code in parallel, which in your case not what you want, you want to wait for the query to finish.
app.post('/create-checkout-session', (req, res) => {
var amount = stringify(req.body)
console.log(req.body.sessionID)
var userId = req.body.sessionID
console.log("email: " + req.body.customer_email)
var email = req.body.customer_email;
var deliveryTotal = req.body.totalWithDelivery;
var totalVal = amount.split("=");
var totalPrice = parseFloat(totalVal[1]);
//console.log("TOTAL PRICE: " + totalPrice);
var finalPrice = parseFloat(Math.round(totalPrice * 100) / 100);
var finalTotal = parseFloat(Math.round(totalPrice * 100) / 100) + parseFloat(Math.round(deliveryTotal));
console.log("final total: " + finalTotal);
var itemName = ""
var itemPrice = ""
var totalNewPriceTest = ""
//query to database
var productsStripe = "select * from " + userId
console.log(userId)
console.log("query to db for displaying cart on stripe page")
ibmdb.open("DATABASE=BLUDB;HOSTNAME=;PORT=50000;PROTOCOL=TCPIP;UID="";PWD="";", function (err,conn) {
if (err) return console.log(err);
conn.query(productsStripe, function (err, rows) {
if (err) {
console.log(err)
}
console.log(rows)
for(var i = 0; i < rows.length; i++) {
itemName = rows[i]['ITEM']
itemPrice = rows[i]['PRICE']
totalNewPriceTest = parseFloat(rows[i]['PRICE'])
console.log("item name : " + itemName + " " + itemPrice )
totalNewPriceTest = parseFloat(totalNewPriceTest);
console.log("final overall prcie: " + (totalNewPriceTest))
}
console.log("inside productsStripe function.")
console.log("overall prcie: " + totalNewPriceTest)
totalNewPriceTest = parseFloat(totalNewPriceTest)
var grandTotal = totalNewPriceTest;
var finalGrandTotal = parseFloat(grandTotal)
console.log(parseFloat(finalGrandTotal))
// continue executing here
//stripe
stripe.checkout.sessions.create({
shipping_address_collection: {
allowed_countries: ['CA'],
},
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'CAD',
product_data: {
name: itemName,
},
unit_amount: finalGrandTotal,
//finalTotal * 100
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'localhost:1001/successPg',
cancel_url: 'localhost:1001/catalogue',
customer_email: email,
}).then((session) => {
console.log(session)
res.json({ id: session.id });
//console.log("customer id" + customer.id)
console.log("totalNewPriceTest " + totalNewPriceTest)
}).catch((err) => {
console.log('stripe err: ', err);
})
})
})
});
Other useful tips to follow:
Don't write business logic inside the router, instead create a controller file and move the logic into it.
Instead of connecting to the DB upon every request, create a DB connection instance and keep it open and available whenever you need it, start with creating its own helper file and then export the connection.

Python selenium close modal window after reading its content

I have the HTML as following:
function showModal(msg) {
var content = document.getElementById("modal-content");
content.innerHTML = msg;
modal.style.display = "block";
}
showModal(msg + "<br>Job started, check status on the project jobs page.");
After all is said and done, I get the following window:
How do I read the content of the box and if there is "Success" I can click the close on top right to go back to the previous page.
I don't have a clue how to approach this.
Edit: Extended HTML looks as following:
function makeInputScenario(ids,params,has_extra = false) {
var sd = gete("sdate").value;
var ed = gete("edate").value;
var sdt = new Date(sd);
var edt = new Date(ed);
if (sdt > edt) {
showModal("Start date is after end date, please fix!");
return;
}
var p = gete("pool").value;
var dzr = gete("dzr").value;
var pfd = gete("pfd").value;
var udb = gete("udb").value;
var uds = gete("uds").value;
if (uds == "None") uds = "";
var rop = gete("rop-text").value;
var fuds = gete("fuds").value;
if (fuds == "None") fuds = "";
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() {
hideProgress();
if (!params) setInteraction(false);
if (xhr.status == 200) {
var msg = "<strong>SUCCESS:</strong><br><pre>" + xhr.responseText + "</pre>"
showModal(msg);
if (params) {
if (has_extra) {
showProgress("Processing, please wait...");
doAction("run-params","POST","/scenario/run","user=PJMRTO LONG RUN AUCTION" + params + "&cir=" + getCir(),function (ret) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<p>" + ret + "</p>");
});
} else {
var ods = gete("ods").value;
showProgress("Adding new job, please wait...");
doAction("run-params","POST","/job","user=PJMRTO LONG RUN AUCTION&sdate=" + sd + "&edate=" + ed + "&ids=" + ids + "&ods=" + ods + "&rops=" + encode(rop) + "&post=" + encode("") + "&std=" + encode("") + "&cir=" + getCir(),function (job) {
showProgress("Starting job " + job + ", please wait...");
doAction("run-params","POST","/run","id=" + job + params,function (x) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<br>Job started, check status on the project jobs page.");
});
});
}
}
} else if (xhr.status == 500) {
setInteraction(false);
clearTimeout(updProgrs);
var logurl = "/idblog?q=host&name=" + encode(ids) + "&pool=" + encode(p) + "&sd=" + encode(sd) + "&ed=" + encode(ed);
showModal(wrapError("<pre>" + xhr.responseText + "</pre><br><button onclick=\"getIDBlog('" + logurl + "');\" class=\"btn btn-primary\">Download Log</button>"));
}
},false);
setInteraction(true);
if (params) {
gete("start-job").style.display = "none";
gete("host-status").style.display = "none";
}
var sparams = "user=PJMRTO LONG RUN AUCTION&pool=" + p + "&dzr=" + dzr + "&pfd=" + pfd + "&ids=" + ids + "&sdate=" + sd + "&edate=" + ed + "&udb=" + udb + "&uds=" + uds + "&rop=" + encode(rop);
if (fuds != "") {
sparams += "&fuds=" + fuds + "&ius=" + gete("ods").value;
showProgress("Creating base and fixed UC input scenarios, please wait...");
} else {
showProgress("Creating input scenario, please wait...");
}
updProgrs = setTimeout(updateProgress, 300000);
xhr.open("POST","/scenario",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("x-csrf-token","NhISQUB1eCANGh46HwsgTnsAISkCAAAATeFn4B0myInXzZc7+8QJMA==");
xhr.send(sparams);
}
So here variable "msg" is storing the value "SUCCESS". It would be better to get the variable "msg" usin javascript.
So that would be :-
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://Reachyourpage")
message = driver.execute_script("return msg")
print ("SUCCESS" in message)
It should return true in case of success. I am no expert in Python but just a beginner so mind my coding.. !!
C# equivalant here would be :-
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
string title = js.ExecuteScript("return msg");
Here, title will have the complete message.
The algorithm is to get the value of "msg" var using javascript.
For Closing the message, have u tried using SendKeys(Keys.Esc) ??
Hope it Helps!!

web3 - event.watch spits out events in random order

I am watching an event:
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
Inside the event I do this tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, ''); Which, long story short, makes a string from the event giving the event from the block (i.e. It gives the event made at block 173).
I then set a <h2> element's text from each event. When this happens it sets them in a seemingly random order. What can be going on, it sets them from block 0 to the latest block, so how can this happen.
Here is the full code: https://pastebin.com/wGt5kL1Y
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
i++;
messages = "";
messages = JSON.stringify(results.args);
if(i === messageToGet) {
if(messages.split(":")[1].split(",")[0] != '""') {
console.log(messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split(",")[0].split("}")[0].split("}")[0] + ")");
tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
} else {
console.log("(No included text)" + "(From: " + messages.split(":")[2].split(",")[0].split("}")[0] + ")");
tempString = (("(no included text) " + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
}
if((messages.split(":")[1].split(",")[0] === undefined) || (messages.split(":")[2].split(")")[0] === undefined)) {
return;
}
if(document.getElementById("Message" + placeToSet) != null) {
document.getElementById("Message" + placeToSet).remove();
if(document.getElementById("hr" + placeToSet) != null) {
document.getElementById("hr" + placeToSet).remove();
}
}
if(document.getElementById("Message" + placeToSet) === null) {
var newh2 = document.createElement('h2');
newh2.setAttribute("id", ("Message" + placeToSet));
var text = document.createTextNode(tempString);
newh2.appendChild(text);
document.body.appendChild(newh2);
var newHR = document.createElement('hr');
newHR.setAttribute("id", ("hr" + placeToSet));
}
}
});

Phonegap Database error

I am trying to set up a database for my phone gap application. the problem is all the transactions apart from the ones setting up the table produce an error saying
"the SQLTransactionCallback was null or threw an exception"
here is the code
function Datasetup()
{
db=window.openDatabase("PracticeData","1.0","saveData",300000);
alert("1");
db.transaction(getDB,onDBError,onDBSuccess);
}
function onDBError(error)
{
alert("Database Error"+error.message);
}
function onDBSuccess(tx,results)
{
alert("successfull");
}
function getDB(tx)
{
alert("2");
tx.executeSql("CREATE TABLE IF NOT EXISTS session(date,length,activity,pieces)");
alert("3");
tx.executeSql("CREATE TABLE IF NOT EXISTS pieces(newpiece,name,composer,youtube,images_src,date_Added)");
alert("4");
tx.executeSql('SELECT * FROM session', [], onSelectSessionSuccess, onDBError());
tx.executeSql("SELECT * FROM session",[],onSelectSessionSuccess,onDBError());
alert("5");
tx.executeSql("SELECT * FROM pieces",[],onSelectPiecesSuccess,onDBError());
}
function savepiece(tx)
{
tx.executeSql("INSERT INTO NOTES(newpiece,name,composer,youtube,images_src,date_Added)VALUES(?,?,?,?,?,?)",[true,pieceData.name,pieceData.composer,"tube","images",date()]);
}
I don't get the error meseges for this or the create table
db.transaction(getDB,onDBError,onDBSuccess)
I get error messages for
tx.executeSql('SELECT * FROM session', [], onSelectSessionSuccess, onDBError());
tx.executeSql("SELECT * FROM session",[],onSelectSessionSuccess,onDBError());
alert("5");
tx.executeSql("SELECT * FROM pieces",[],onSelectPiecesSuccess,onDBError());
that was a great help now one of my selects work the other one however comes up with
"the statement callback raised an exception or statement error callback did not return false"
here's the sql that's not working
tx.executeSql('SELECT * FROM session', [],onSelectPiecesSuccess, onDBError);
here is the updated code
function Datasetup(){
db=window.openDatabase("PracticeData","1.0","PracticeData",300000);
db.transaction(getDB,onDBError,onDBSuccess);
}
function onDBError(error){
alert("Database Error "+error.message);
}
function onDBSuccess(tx,results){
//db.transaction(query,onDBError);
db.transaction(query,onDBError);
alert("before");
}
function getDB(tx){
//alert("dropping")
//tx.executeSql("DROP TABLE pieces");
tx.executeSql("CREATE TABLE IF NOT EXISTS session(date,length,activity,pieces)");
tx.executeSql("CREATE TABLE IF NOT EXISTS pieces(newpiece,name,composer,youtube,images_src,date_added)");
//tx.executeSql('INSERT INTO session(date, length, activity,pieces) VALUES ("10-2-12", "15","2","11")');
//tx.executeSql('INSERT INTO session (date, length, activity,pieces) VALUES ("11-2-12", "15","2","11")');
//tx.executeSql('INSERT INTO session (date, length, activity,pieces) VALUES ("12-2-12", "15","2","11")');*/
tx.executeSql('INSERT INTO session (date, length, activity,pieces) VALUES ("13-2-12", "15","2","violin")');
tx.executeSql('INSERT INTO pieces (newpiece, name, youtube,images_src,date_Added) VALUES ("true", "15","tube","11",13-9-13)');
//tx.executeSql("DROP TABLE pieces");
//tx.executeSql("DROP TABLE session");
//alert("vi");
}
/**sessions**/
function query(tx){
tx.executeSql('SELECT * FROM session', [], onSelectSessionSuccess, onDBError);
}
function onSelectSessionSuccess(tx,results){
dbResult = results;
var len= results.rows.length;
var sessionList="";
for(var i=0;i<len;i++)
{
sessionList = sessionList+"<li>"+results.rows.item(i).date+"</li>"
}
alert(sessionList);
//tx.executeSql("SELECT * FROM pieces",[],onSelectPiecesSuccess,onDBError());
db.transaction(piecesquery,onDBError);
}
/**pieces**/
function piecesquery(tx){
//alert("piecesquery");
tx.executeSql('SELECT * FROM session', [],onSelectPiecesSuccess, onDBError);
}
function onSelectPiecesSuccess(tx,results){
var len= results.rows.length;
var PiecesList="";
var newPiecesList="";
var res;
alert(len);
for(var i=0;i<len;i++)
{
newPiecesList=newPiecesList+"<li>"+results.rows.item(i).newpiece + results.rows.item(i).composer +"</li>"
}
alert(newPiecesList);
$('#newPiecesList').innerHTML(newPiecesList);
}
my flow:
the tables are created and populated getDB.
session data is pulled on the success of getDb.
pieces data is pulled when the session page initiates. But i can replace the code to pull the pieces table with the code to pull from session table with no problems.
for some reason it seems that the data going into the pieces table isn't accessible
I have done table creation,insert and select process.Hope it will be useful.
var db=null;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = window.openDatabase("TestDatabase","1.0","TestingDatabase",'200000000');
alert("db1");
db.transaction(populateDatabase,errorDb,successDb);
}
function populateDatabase(tx){
tx.executeSql('DROP TABLE IF EXISTS TestTable');
tx.executeSql('CREATE TABLE IF NOT EXISTS TestTable(RollNo INT PRIMARY KEY,FirstName text,LastName text,MobileNo text)');
tx.executeSql('INSERT INTO TESTTABLE (RollNo, FirstName, LastName, MobileNo) VALUES (1, "Nisari", "Balakrishnan", "8891924207")');
tx.executeSql('INSERT INTO TESTTABLE (RollNo, FirstName, LastName, MobileNo) VALUES (2, "Mikhil", "Anandan", "9605432101")');
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM TESTTABLE', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
var len = results.rows.length;
alert(len);
console.log("DEMO table: " + len + " rows found.");
for (var i=0; i<len; i++){
//console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data);
alert("Row = " + i + " ID = " + results.rows.item(i).RollNo + " FirstName = " + results.rows.item(i).FirstName + " LastName = " + results.rows.item(i).LastName + " MobileNo = " + results.rows.item(i).MobileNo);
// db = window.openDatabase("TestDatabase","1.0","TestingDatabase",'200000000');
// db.transaction(updateDB, errorCB);
// console.log("After Open DB");
}
}
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
function errorDb()
{
alert("Error on Database creation:" + Error);
}
function successDb()
{
alert("Database is created successfully");
db = window.openDatabase("TestDatabase","1.0","TestingDatabase",'200000000');
db.transaction(queryDB, errorCB);
}
executeSql for SELECT query is an asynchronous command. The 'onSelectSessionSuccess' is the callback function in which you'll receive the result from the table.
Since these are async calls, execution won't wait for the data to be returned by the query.
Place your next SELECT call as a part of the success callback of the previous call.
i.e you should select pieces in the success callback 'onSelectSessionSuccess' and things would work absolutely fine.
Hope that helps.

Slightly modify lat/lng for gmap api v3

Have a quick question. On my website I have a form that allows users to input their city, state, and country. This information is converted to $lat and $lng, which is used to create a marker on a google map. Problem is, I have multiple users that select the same city. Clustering is a HUGE pain... to be honest, I can't seem to find a good tutorial and I'm feeling a bit hopeless.
So I thought I'd just modify each $lat and $lng slightly. For example, this is the info I get for Travis AFB, CA: lat="38.263065" lng="-121.949699". Wondering if it's possible to add a bit of code that might let me modify those last bits. Any suggestions???
Here's how I geocode $address (combination of $city, $state, $country):
$geocodestring=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' . urlencode($address) );
$geocodedinfo=json_decode($geocodestring);
$lat = $geocodedinfo->results[0]->geometry->location->lat;
$lng = $geocodedinfo->results[0]->geometry->location->lng;
And that information goes into my SQL database. This is the code that actually creates the map (pretty straightforward).
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 2);
map.enableScrollWheelZoom();
GDownloadUrl("world_xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var first_name = markers[i].getAttribute("first_name");
var last_name = markers[i].getAttribute("last_name");
var email = markers[i].getAttribute("email");
var affiliation = markers[i].getAttribute("affiliation");
var status = markers[i].getAttribute("status");
var service = markers[i].getAttribute("service");
var rank = markers[i].getAttribute("rank");
var specialty = markers[i].getAttribute("specialty");
var city = markers[i].getAttribute("city");
var state = markers[i].getAttribute("state");
var country = markers[i].getAttribute("country");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, rank, first_name, last_name, email, affiliation, status, service, specialty, city, state, country) {
var marker = new GMarker(point);
var html = "" + rank + " " + first_name + " " + last_name + " " + service + ", " + status + " " + specialty + " " + affiliation + " " + city + ", " + state + " " + country + " " + email + " " + " ";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
Any help/suggestions would be much appreciated!!!
Jeremy
markerclusterer for v2 may solve your problem.
Find code and examples here
http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0/