I'm having trouble exporting or downloading information to a file. It works fine in my browser, but when I try it in my phonegap app, the file just opens as text without an option to save it or return to the app. Any advice? Keep in mind that I'm not very experienced with JavaScript - more of a beginner!
function dbError(e) {
console.log("SQL ERROR");
console.dir(e);
}
function backup(table) {
var def = new $.Deferred();
curatio.webdb.db.readTransaction(function(tx) {
tx.executeSql("select * from "+table, [], function(tx,results) {
var data = convertResults(results);
console.dir(data);
def.resolve(data);
});
}, dbError);
return def;
}
$(document).on("click", "#doBackupBtn", function(e) {
e.preventDefault();
console.log("Begin backup process");
$.when(
backup("allergies")
).then(function(allergies, log) {
console.log("All done");
var data = {allergies:allergies}
var serializedData = JSON.stringify((data), null, 4);
console.log(serializedData);
download("Export.csv", serializedData);
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
});
});
function download(filename, content) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
pom.setAttribute('download', filename);
pom.click();
}
//Generic utility
function convertResults(resultset) {
var results = [];
for(var i=0,len=resultset.rows.length;i<len;i++) {
var row = resultset.rows.item(i);
var result = {};
for(var key in row) {
result[key] = row[key];
}
results.push(result);
}
return results;
}
</script>