i'm getting the error : Uncaught ReferenceError: errorHandler is not defined at file:
what am i doing wrong? source code: http://pastebin.com/3203ynUB
i iniate the first piece with onclick="startBackup()"
it seems to go wrong somewhere in retrieving data from the database, but i cant figure out how and where.
the database is as following
DBName: SmartPassDB
Table name: SmartPass
rows: id , name , nickName , passID , Website
// change to your database
var db = window.openDatabase("Database", "1.0", "SmartPassDB", 5*1024); // 5*1024 is size in bytes
// file fail function
function failFile(error) {
console.log("PhoneGap Plugin: FileSystem: Message: file does not exists, isn't writeable or isn't readable. Error code: " + error.code);
alert('No backup is found, or backup is corrupt.');
}
// start backup (trigger this function with a button or a page load or something)
function startBackup() {
navigator.notification.confirm('Do you want to start the backup? This will wipe your current backup. This action cannot be undone.', onConfirmBackup, 'Backup', 'Start,Cancel');
}
// backup confirmed
function onConfirmBackup(button) {
if(button==1) {
backupContent();
}
}
// backup content
function backupContent() {
db.transaction(
function(transaction) {
transaction.executeSql(
// change this according to your table name
'SELECT * FROM SmartPass;', null,
function (transaction, result) {
if (result.rows.length > 0) {
var tag = '{"items":[';
for (var i=0; i < result.rows.length; i++) {
var row = result.rows.item(i);
// expand and change this according to your table attributes
tag = tag + '{"id":"' + row.attribute1 + '","name":"' + row.attribute2 + '","nickName":"' + row.attribute3 + '","passId":"' + row.attribute4 + '","website":"' + row.attribute5 + '"}';
if (i+1 < result.rows.length) {
tag = tag + ',';
}
}
tag = tag + ']}';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
// Change the place where your backup will be written
fileSystem.root.getFile("backup.txt", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.write(tag);
}, failFile);
}, failFile);
}, failFile);
alert("Backup done.");
} else {
alert("No content to backup.");
}
},
errorHandler
);
}
);
}
// start restore (trigger this function with a button or a page load or something)
function startRestore() {
navigator.notification.confirm('Do you want to start the restore? This will wipe your current data. This action cannot be undone.', onConfirmRestore, 'Restore', 'Start,Cancel');
}
// restore confirmed
function onConfirmRestore(button) {
if(button==1) {
restoreContent();
}
}
// restore content
function restoreContent() {
db.transaction(
function(transaction) {
transaction.executeSql(
// change this according to your table name
'DELETE FROM SmartPass', startRestoreContent()
);
});
}
// actually start restore content
function startRestoreContent() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
// Change the place where your backup is placed
fileSystem.root.getFile("backup.txt", null, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var data = JSON.parse(evt.target.result);
var items = data.items;
count = items.length;
db.transaction(
function(transaction) {
$.each(items, function(index, item) {
transaction.executeSql(
// change and expand this according to your table name and attributes
'INSERT INTO SmartPass (id, name, nickName, passId, website) VALUES (?, ?, ?, ?, ?)',
[item.attribute1, item.attribute2, item.attribute3, item.attribute4, item.attribute5],
null
);
});
});
};
reader.readAsText(file);
alert("Restore done.");
}, failFile);
}, failFile);
}, failFile);
}
As per the error
error : Uncaught ReferenceError: errorHandler is not defined at file:
The function errorHandler is not defined in the code.
In your function backupContent() {..} you have used errorHandler as callback reference for the transaction.executeSql() call.
transaction.executeSql(....,errorHandler)
You need to define the errorHandler function.
Also you need to consider a scenario as to how do you handle initial database load. If you run the code for the first time there will not be any tables. The following sql statement will fail.
SELECT * FROM SmartPass;
The table SmartPass is not yet created. That is the most likely reason of the errorHandler being called.
Related
Using parse.com and JavaScript SDK.
I've searched, but cannot find a good answer for this.
This function works when I use just use current user. However what it should do is use the value stored in the variable friendRequest to query results that already exist in parse. The FriendRequest variable is populated once the user clicks on one of the images being displayed on the page within the div id container
I get the following error and I'm not sure how to fix it? Is it because FriendRequest is undefined?
Uncaught Error: Can't serialize an unsaved Parse.Object
Screen shot attached.
Here is the function returning the error.
function FriendProfile() {
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", friendRequest);
query.find({
success: function (results) {
// If the query is successful, store each image URL in an array of image URL's
imageURLs = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
imageURLs.push(object.get('BadgeName'));
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
for (var j = 0; j < imageURLs.length; j++) {
$('#imgs').append("<img src='" + imageURLs[j] + "'/>");
}
},
error: function (error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
}
Here is how the friendRequest variable is populated .
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper" data-friend-request-id="' + item.friendRequestId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
///SECTION 2 -Click/Select friend image to be captured and used with section 3//////////
// set up event handler
$('#container').on('click', '.wrapper', function () {
console.log(this);
FriendProfile();
var wrapper = $(this);
console.log(wrapper.data('friendRequestId'));
// remove selected from all wrappers in case one was already selected
$('#container .wrapper').removeClass('selected');
// mark clicked wrapper as selected
wrapper.addClass('selected');
// save friendRequestId as a global that can be read by other code
window.selectedFriendRequestId = wrapper.data('friendRequestId');
// enabled button
$('#simulateAddBadge').removeAttr('disabled');
});
$(document).ready(function () {
$('.go').css('cursor', 'pointer');
$('.go').click(function (e) { // Button which will activate our modal
$(this).width(100).height(100).appendTo('#badgeselect');
});
return false;
});
If window.selectedFriendRequestId is not set when FriendProfile() is called, then you will get an error. Add console.log(window.selectedFriendRequestId); in there to help you debug.
You need to examine the logic you are after, you might instead want to make the friendRequestId a parameter of the function and extract the value in the click handler and pass it as a parameter. Currently your "SECTION 2" code is calling the function then setting the value afterwards.
Simplified example:
function FriendProfile(friendRequestId) {
// query based on friendRequestId ...
}
// other code that calls function
$('#container').on('click', '.wrapper', function () {
var wrapper = $(this);
var friendRequestId = wrapper.data('friendRequestId');
FriendProfile(friendRequestId);
// other code ...
});
var dbShell;
function doLog(s){
/*
setTimeout(function(){
console.log(s);
}, 3000);
*/
}
function dbErrorHandler(err){
alert("DB Error: "+err.message + "\nCode="+err.code);
}
function phoneReady(){
doLog("phoneReady");
//First, open our db
dbShell = window.openDatabase("SimpleNotes", 2, "SimpleNotes", 1000000);
doLog("db was opened");
//run transaction to create initial tables
dbShell.transaction(setupTable,dbErrorHandler,getEntries);
doLog("ran setup");
}
//I just create our initial table - all one of em
function setupTable(tx){
doLog("before execute sql...");
tx.executeSql("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY,title,body,updated)");
doLog("after execute sql...");
}
//I handle getting entries from the db
function getEntries() {
//doLog("get entries");
dbShell.transaction(function(tx) {
tx.executeSql("select id, title, body, updated from notes order by updated desc",[],renderEntries,dbErrorHandler);
}, dbErrorHandler);
}
function renderEntries(tx,results){
doLog("render entries");
if (results.rows.length == 0) {
$("#mainContent").html("<p>You currently do not have any notes.</p>");
} else {
var s = "";
for(var i=0; i<results.rows.length; i++) {
s += "<li><a href='edit.html?id="+results.rows.item(i).id + "'>" + results.rows.item(i).title + "</a></li>";
}
$("#noteTitleList").html(s);
$("#noteTitleList").listview("refresh");
}
}
function saveNote(note, cb) {
//Sometimes you may want to jot down something quickly....
if(note.title == "") note.title = "[No Title]";
dbShell.transaction(function(tx) {
if(note.id == "") tx.executeSql("insert into notes(title,body,updated) values(?,?,?)",[note.title,note.body, new Date()]);
else tx.executeSql("update notes set title=?, body=?, updated=? where id=?",[note.title,note.body, new Date(), note.id]);
}, dbErrorHandler,cb);
}
function init(){
document.addEventListener("deviceready", phoneReady, false);
//handle form submission of a new/old note
$("#editNoteForm").live("submit",function(e) {
var data = {title:$("#noteTitle").val(),
body:$("#noteBody").val(),
id:$("#noteId").val()
};
saveNote(data,function() {
$.mobile.changePage("index.html",{reverse:true});
});
e.preventDefault();
});
//will run after initial show - handles regetting the list
$("#homePage").live("pageshow", function() {
getEntries();
});
//edit page logic needs to know to get old record (possible)
$("#editPage").live("pageshow", function() {
var loc = $(this).data("url");
if(loc.indexOf("?") >= 0) {
var qs = loc.substr(loc.indexOf("?")+1,loc.length);
var noteId = qs.split("=")[1];
//load the values
$("#editFormSubmitButton").attr("disabled","disabled");
dbShell.transaction(
function(tx) {
tx.executeSql("select id,title,body from notes where id=?",[noteId],function(tx,results) {
$("#noteId").val(results.rows.item(0).id);
$("#noteTitle").val(results.rows.item(0).title);
$("#noteBody").val(results.rows.item(0).body);
$("#editFormSubmitButton").removeAttr("disabled");
});
}, dbErrorHandler);
} else {
$("#editFormSubmitButton").removeAttr("disabled");
}
});
}
Dats my code, awfully long, huh?
Well anyways I got most of it from here, however I get an error on line 67 saying "TypeError: 'undefined' is not a function.".
I'm using Steroids (phonegap-like) and testing dis on an iPhone simulator. I'm sure it uses some cordova for the database work.
Thank you for your help :-)
Which jQuery version do you use? Because .live() was removed with jQuery 1.9 (http://api.jquery.com/live/). You should use .on() instead: http://api.jquery.com/on/
I have a enhancegrid which fields are editable. Some fields will be changed manually while others will change dynamically. The thing is that I would not want to store values onApplyEdit, I want to force save the values but I cant find the solution for it. Here is how it´s right now which actually working great.
dojo.connect(grid, "onApplyEdit", grid, function(evt, rowIndx, fieldIndx){
var selected_item = grid.getItem(evt);
//Not sure if this is the most efficient way but it worked for me
var row_id = grid.store.getValue(selected_item, "row_id");
var from_item_no = grid.store.getValue(selected_item, "from_item_no");
var from_inventory = grid.store.getValue(selected_item, "from_inventory");
var comment = grid.store.getValue(selected_item, "comment");
edit_quantity = grid.store.getValue(selected_item, "quantity");
var to_item_no = grid.store.getValue(selected_item, "to_item_no");
var to_inventory = grid.store.getValue(selected_item, "to_inventory");
var foundation = grid.store.getValue(selected_item, "foundation");
// Instantiate some write implementing store.
var store = grid.store;
// Set our load completed handler up...
var onCompleteFetch = function(items, request){
// Define the save callbacks to use
var onSave = function(){
dojo.xhrPost({
url: url,
content: {
row_id: row_id,
from_item_no: from_item_no,
from_inventory: from_inventory,
comment: comment,
quantity: edit_quantity,
to_item_no: to_item_no,
to_inventory: to_inventory,
foundation: foundation
},
handleAs: "text",
load: function(data){
console.log("Returned value: " + data);
global_saved_check = false;
},
error: function(error){
alert(error);
}
});// end xhrPost
} // end onSave
var onSaveError = function(error){
alert("Error occurred: " + error);
}
// If the store has modified items (it should), call save with the handlers above.
if(store.isDirty()){
store.save({onComplete: onSave, onError: onSaveError});
}
} // end onCompleteFetch
// Define a fetch error handler, just in case.
var onFetchError = function(error, request){
alert("Fetch failed. " + error);
}
// Fetch some data... All items with a foo attribute, any value.
store.fetch({query: {foo:"*"}, onComplete: onCompleteFetch});
});//end connect onApplyEdit
I'm currently using phonegap to create and ios app.
While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.
I'm currently using the following creation code (from the phonegap wiki)
var mydb=false;
// initialise the database
initDB = function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'phonegap';
var version = '1.0';
var displayName = 'PhoneGap Test Database';
var maxSize = 65536; // in bytes
mydb = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
// Error handling code goes here.
if (e == INVALID_STATE_ERR) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
}
// db error handler - prevents the rest of the transaction going ahead on failure
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
return true;
}
// null db data handler
nullDataHandler = function (transaction, results) { }
my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?
and secondly how can i drop all these databases that have been created.
transaction.executeSql('DROP DATABASE phonegap;');
does not seem to drop anything.
Thanks
Please try following code. it is not creating multiple database files, just cross verify by visiting location -/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0
This is sqlite3 example which cover create, insert, delete and drop queries on Table.
<!DOCTYPE html>
<html>
<body style="font: 75% Lucida Grande, Trebuchet MS">
<div id="content"></div>
<p id="log" style="color: gray"></p>
<script>
document.getElementById('content').innerHTML =
'<h4>Simple to do list</h4>'+
'<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
'<button onclick="newRecord()">new record</button>'+
'<button onclick="createTable()">create table</button>' +
'<button onclick="dropTable()">drop table</button>';
var db;
var log = document.getElementById('log');
db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
showRecords();
document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
function onError(tx, error) {
log.innerHTML += '<p>' + error.message + '</p>';
}
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i < result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['id']+' '+item['text'] + '</span> x</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
function(tx) { log.innerHTML = 'Table1Test created' },
onError);
});
}
// add record with random values
function newRecord() {
var num = Math.round(Math.random() * 10000); // random data
db.transaction(function(tx) {
tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
function(tx, result) {
log.innerHTML = 'record added';
showRecords();
},
onError);
});
}
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
function(tx, result) { showRecords() },
onError);
});
}
// delete table from db
function dropTable() {
db.transaction(function(tx) {
tx.executeSql("DROP TABLE Table1Test", [],
function(tx) { showRecords() },
onError);
});
}
</script>
</body>
</html>
And about Droping Database...
Does not seem meaningful for an embedded database engine like SQLite. To create a new database, just do sqlite_open(). To drop a database, simply delete the file.
thanks,
Mayur
Manually deleting the SQLite database from the Library worked for me. Thanks for the precious tip.
I am new to Android-Phonegap dev. I am creating a project using Eclipse in Windows XP.
I am using sqlite database. I saw the sample code in the docs. But I'm not able to execute this example. I am not getting the required results.
Suppose I want to get all the entries in the table demo in tabular format, HTML. What will the code be in index.html? For that, what is the procedure and what is the step by step procedure for doing this? Or else any better tutorials which help me to do this?
Thanks in Advance
Dnyan.
in main.js you add this
rowsDataHandler = function(transaction, results) {
// Handle the results
var html = "<ul>";
for (var i=0; i<results.rows.length; i++) {
var row = results.rows.item(i);
html += '<li>'+row['data']+'</li>\n';
}
html +='</ul>';
document.getElementById("mydata").innerHTML = html;
}
// load the currently selected icons
loadRows = function(db) {
try {
db.executeSql('SELECT * FROM DEMO',[], rowsDataHandler, errorCB);
} catch(e) {alert(e.message);}
}
in index.html you add this row inside body
<div id="mydata"></div>
One thing to bear in mind is that if you aren't testing the application on a device or in an emulator, but rather in a browser like Chrome or Safari,
document.addEventListener("deviceready", onDeviceReady, false);
won't work. What I've done is to comment out this line and just to put in a call to
onDeviceReady();
When I then test in the emulator I uncomment the "document…" line and comment out
onDeviceReady();
**html**
<input id="show" type="button" value="Show">
**js**
function globalError(tx, error)
{
alert("Error: " + error.message);
}
var db = window.openDatabase('TabOrder', '', 'Bar Tab Orders', 2500000);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS SubmiteData;', null, null, globalError);
tx.executeSql('CREATE TABLE IF NOT EXISTS SubmiteData (SubmiteDataId integer
primary key, UserId text, AuthNo number, LocId number,ProdId number,
CardId number, OrgLat text, OrgLng text, OrgTime text)',
null,
function()
{
SubmiteData("USER1",12345678,23434, 21212, 220232,
"9", "45", "23/06/2014");
},
globalError);
});
function SubmiteData(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx){
tx.executeSql('INSERT INTO SubmiteData(UserId, AuthNo, LocId, ProdId, CardId,
OrgLat, OrgLng, OrgTime) VALUES (?,?,?,?,?,?,?,?)', [UserId, AuthNo, LocId,
ProdId, CardId, OrgLat, OrgLng, OrgTime],
null,
globalError
);
});
}
function read(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM SubmiteData',
[],
function(tx, results)
{
for (var i=0; i<results.rows.length; i++)
{
var row=results.rows.item(i);
// alert("Id: " + row['UserId']);
var stringout = "LocId: " + row['LocId'] + "\n";
alert(stringout);
}
},
globalError
);
});
};
$(function()
{
$('#show').click(read);
});
this is the method to connect to a db using javascript
db = openDatabase("bprueba","1.0","Prueba_db",5*1023*1024);
SQL Statement Error Callback Reference