Reputation: 13
I'm doing some work with WebSQL: creating an object to send via ajax to a server-side script to do some more complex work. I've read a couple dozen tutorials on similar tasks, but for whatever reason, my code returns an empty object as a result of JSON.stringify():
function submit_entries(){
url = "http://myurl.com/process.cfm"
send_data = new Object();
db.transaction(function(tx){
tx.executeSql('SELECT * FROM mytable', [], function(tx, results){
var len = results.rows.length, i;
for(var i = 0; i <len; i++){
send_data["person"+i] = {};
send_data["person"+i].fname = results.rows.item(i).fname;
}
});//end tx.executeSql
});//end db.transaction
send_ajax(send_data);
}
function send_ajax(send_data){
console.log(send_data); // log 1
var send_str = JSON.stringify(send_data);
console.log(send_str); //log 2
console.log($.parseJSON(send_str)); //log 3
/*$.ajax({
url: url,
data: send_str,
type: "post",
contentType: "application/json",
dataType: 'json',
success: function(){
console.log('yay it might have worked.')
}
})*/
}
The first log will output an object. The second an empty set of braces "{}" and the third will output an empty object. I've tried this without the nested "person"+i objects and get the same results.
Upvotes: 1
Views: 1541
Reputation: 69964
Looks like your db.transaction is asynchronous. If this is the case, it will not have run by the time you get to the send_ajax call.
Try putting the send_ajax call inside the function(tx, results){ ... }
callback.
Upvotes: 2