I am working on a phonegap app, and have so far set-up the database to which I have the insert and delete function's working correctly.
I am now struggling on checking input values with the data in the database, so for example for now I am just simply attempting to check if any rows are returned, and if there is that will mean the user and pass entered are in the database, if no rows are returned then the user and pass is false.
I am not getting any errors from the sql statement (function errorCB), as well I did put an debug alert within the function LoginSuccess and that worked, however after removing the debug alert in the LoginSuccess function, I do not get prompted with any alerts and instead the page just refreshes.
I have removed the delete and insert functions from the code as it's relevant to this issue.
Any help will be much appreciated.
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(createDB, errorCB, successCB);
}
function createDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS mahdi (FirstName text, LastName text, Email text, Password text)');
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
alert("Database Ready");
}
function loginUser()
{
db = window.openDatabase("DBkhan", "1.0", "SFDatabase", 2*1024*1024);
db.transaction(loginDB, errorCB, LoginSuccess);
}
function loginDB(tx)
{
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'");
} function LoginSuccess(tx, results) {
if (results.rows.length > 0) {
alert ("User and Pass Found");
}
else
{
alert ("User and Pass incorrect");
}
}
Don't worry, all fixed. See below if you'd like to see what I changed around. Seem's as though it was the missing array [] in the executesql statement and calling the renderList (changed from loginSuccessful) into the exectutesql statementent.
function loginDB(tx)
{
alert("yep yep yep");
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM mahdi WHERE FirstName='" + Username + "' AND Password= '" + Password + "'", [], renderList);
}
function renderList(tx,results) {
if (results.rows.length > 0) {
navigator.notification.alert("User and Pass Found");
}
else
{
navigator.notification.alert("User and Pass incorrect");
}
}
Related
I have .js file where I loop through Firebase real time database to find email and password of registered users which is stored under /users tree in database where each child is randomly generated unique id which has user information. I am getting email and password information from form element. Problem is the alert messages in checkMessage are not executed when email and password do not equal same. Alert message should be displayed but only page refreshes.
Database:
----/Users
--------/XJIGFDMDKGD
-------------email: "a#b.com"
-------------password: "12345"
--------/XJFGNRIENGJ
-------------email: "c#d.com"
-------------password: "67890"
My code:
document
.getElementById('loginForm')
.addEventListener('submit', formSubmit);
function formSubmit(e) {
e.preventDefault();
document.querySelector('.alert').style.display = 'block';
// Get Values from the DOM
let email = document.querySelector('#email').value;
let password = document.querySelector('#password').value;
//check message values
checkMessage(email, password);
//Form Reset After Submission
//document.getElementById('loginForm').reset();
}
checkMessage function:
function checkMessage(email, password) {
var usrs = firebase.database().ref('users');
usrs.on("child_added", function(snapshot) {
var user = snapshot.val();
if (user.email == email) {
if (user.password == password) {
} else {
}
} else {
document.querySelector('.alert2').style.display = 'block';
setTimeout(function() {
document.querySelector('.alert2').style.display = 'none';
}, 7000);
document.getElementById('loginForm').reset();
}
);
}
The error was caused by syntax problem, an extra brace at the end of the following section of code, as well as a misplaced parentheses. Fixed solution:
var users = firebase.database().ref('users');
users.on("child_added", function(snapshot) {
var user = snapshot.val();
if (email == user.email) {
if (password == user.password) {
}
} else {
};
});
I have the following code but it dosent work and i dont know where the error is
var username= document.getElementById("demo-Username").value;
var password= document.getElementById("demo-Password").value;
alert(username);
db.transaction(function (tx) {
alert("before select");
tx.executeSql("SELECT * FROM user WHERE username=? AND password=?",[username,password],function (tx,results){
alert("after select");
var len = results.rows.length, i;
if(len>0){
alert("Welcom");
}else {
alert("ERROR USERNAME OR PASSWORD");
}
}, null);
});
it works until reach to the select statement and stop working, if i remove the function that located after the select statement it works and the same thing if i remove the select statement and keep the function it also works but when i put them together it will stop executing in select statement.
anyone know what the error here ?
I build an mobile app hibrid base with phonegap and jquery mobile. My app has a login system, retrieve data from database in server and insert it to sqlite when login succes, so the app can access to the data even it's offline.
i use plugin from litehelpers. And this my sql connect script in database.js:
document.addEventListener("deviceready", connectDB, false);
var kode = JSON.parse(window.localStorage['konfirmasi']);
//create or open Database
function connectDB(){
db = window.sqlitePlugin.openDatabase("konfirmasi", "1.0", "Data Konfirmasi Pengiriman", "1000");
db.transaction(populateDB,successCB,errorCB);
}
//create table and insert some record
function populateDB(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS data_konfirmasi (kode_transaksi text, status text) UNIQUE(kode_transaksi)");
}
//function will be called when an error occurred
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
console.log("Connected to database!");
//db.transaction(queryDB,errorCB);
}
function insertDB(tx){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql("INSERT INTO data_konfirmasi VALUES ("+kode[i]+", 'Belum Terkirim');");
};
}
function queryDB(){
db.transaction(insertDB,errorCB,querySuccess);
}
function querySuccess(){
console.log('Insert query success!');
}
function dropDB(){
db.transaction(dropQuery,errorDrop,successDrop);
}
function dropQuery(tx){
tx.executeSql("DROP TABLE IF EXIST data_konfirmasi");
}
function successDrop(){
console.log('Drop table successful');
}
function errorDrop(err){
console.log('Drop table unsuccessful, Error code: '+err.code);
}
function selectData(err){
db.transaction(selectQuery, errorCB, successQuery)
}
function selectQuery(tx){
tx.executeSql('SELECT * FROM data_konfirmasi',[], querySuccess, errorCB);
}
function querySuccess(tx, results) {
console.log("Returned rows = " + results.rows.length);
// this will be true since it was a select statement and so rowsAffected was 0
if (!results.rowsAffected) {
console.log('No rows affected!');
return false;
}
// for an insert statement, this property will return the ID of the last inserted row
console.log("Last inserted row ID = " + results.insertId);
}
Then, when user login for the first time and success it will retrieve data from server with json, and i want my app to insert retrieved data to sqlite. So, how to put the query for login success only? After that i want to make it DROP table and clear localStorage when it's logout.
This is my login and logout script (main.js):
$(document).on('pageinit','#login',function(){
$(document).on('click','#submit',function(){
if($('#username').val().length>0&&$('#password').val().length>0){
var un = $('#username').val();
var pw = $('#password').val();
$.ajax({
url:'http://qrkonfirmasi.16mb.com/delivery/login.php',
data:{ username : un,
password : pw
},
type:'post',
async:'false',
dataType: 'json',
beforeSend:function(){
$.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
},
complete:function(){
$.mobile.loading('hide');
},
success:function(result){
console.log(result);
if(result.status==true){
user.name=result.message;
window.localStorage.setItem('konfirmasi', JSON.stringify(result.data));
console.log('Kode: ', JSON.parse(window.localStorage['konfirmasi']));
var kode = JSON.parse(window.localStorage['konfirmasi']);
console.log('Array length: '+kode.length);
queryDB();
console.log('Login berhasil');
$.mobile.changePage("#konfirmasi");
window.localStorage.setItem('uname', un);
window.localStorage.setItem('passwd', pw);
console.log(window.localStorage['uname']);
}else{
alert('Login gagal. Username atau password tidak sesuai');
}
},
error:function(request,error){
alert('Koneksi error. Silahkan coba beberapa saat lagi!');
}
});
}else{
alert('Masukkan username dan password!');
}
return false;
});
});
$(document).on('pagebeforeshow','#konfirmasi',function(){
$.mobile.activePage.find('.welcome').html('<h3>Selamat Datang '+user.name+'</h3>' );
});
$(document).off('click').on('click','#logout',function(){
window.localStorage.clear();
dropDB();
$.mobile.changePage("#home");
});
function exitFromApp(){
navigator.app.exitApp();
}
So, am i at the right way for logout script? I didn't know it works or not because i still cannot try it because the login script still error when i try it with insert query.
Can someone help me make it done, please?
Where are u calling this piece of code from?
function insertDB(tx,val){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql('INSERT INTO konfirmasi VALUES ('+a[i]+');',querySuccess,errorCB);
};
}
If you are calling it from a transaction, then the "val" parameter will not be passed to the insertDB function directly. You might try the following thing:
val = [];
db.transaction(function(tx){
insertDB(tx, val);
}, errorCB);
Moreover, make sure that the stements always run within a db.transaction context
Have fun!
i'm gettin sql processing error sql:underfined here.Here i'm check whether the login form matched with the database called student and if there is a matched then an alert popup with welcome message and transfer to the next page.How do i fix the code?
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "Student",2*1024*1024);
db.transaction(createDB, errorCB, successCB);
}
function loginForm(){
db.transaction(checkDB, errorCB);
$.mobile.changePage("#page5",{reverse:false,transition:"slide"});
return false;
}
function checkDB(tx){
var _matric=$("[name='matric']").val();
var _password=$("[name='password']").val();
var sql ='select * from STUDENT where matric='+_matric+' and password='+_password+'';
tx.executeSql(sql,[],successLoginDB,errorCB);
}
function successLoginDB(tx,results){
var len = results.rows.length;
var _name =$("[name='name']").val();
if (len==1) {alert("Welcome "+_name);}
}
First you code is vulnerable to SQL Injection, fix it using args:
function loginForm(){
db.transaction(checkDB, errorCB);
$.mobile.changePage("#page5",{reverse:false,transition:"slide"});
return false;
}
function checkDB(tx){
var matric=$("[name='matric']").val();
var password=$("[name='password']").val();
var sql ='select * from STUDENT where matric = ? and password = ?';
tx.executeSql(sql,[matric, password],successLoginDB,errorCB);
}
function successLoginDB(tx,results){
var len = results.rows.length;
var name =$("[name='name']").val();
if (len==1) {alert("Welcome "+name);}
}
About error; I'm sure you are trying to use webSQL before cordova loads. You need wait for "DOM Ready" (for read text inputs) and "deviceready" for access to WebSQL:
document.addEventListener("deviceready", onDeviceReady, false);
var onDeviceReady = function () {
// Start here.
}
Please, post more info.
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.