IndexedBD and localStorage undefined error - javascript

I have an indexedDB which im trying to use to capture form information on user registration. That part is working fine but the prof wants an account to be create once with the username and password set on creation so he can log in.
The way I approached this was with a localStorage API. I created a function to check if the admin account had ever been created, and if not to create it calling the addAdmin() function.
I tried to create addAdmin() by copying my addObject() but for some reason my db variable is returning as undefined in the console.
Error" Uncaught TypeError: Cannot call method 'transaction' of undefined
var mainForm, fName, lName, uName, pass, email, dob, phone, bio, nl, terms, school, gender, save, reset, db;
//-------------USER DB------------------//
function startDB(){
mainForm = document.getElementById('mainFormSidebar');
fname = document.getElementById('fName');
lName = document.getElementById('lName');
users = document.getElementById('uName');
pass = document.getElementById('password');
email = document.getElementById('email');
dob = document.getElementById('dob');
phone = document.getElementById('phone');
bio = document.getElementById('bio');
nl = document.getElementById('newsletter');
terms = document.getElementById('terms');
school = document.getElementById('school');
gender = document.getElementsByName('gender');
save = document.getElementById('save');
reset = document.getElementById('reset');
reset.addEventListener('click',clearForm);
databox = document.getElementById('databox');
mainForm.addEventListener('submit',addObject);
//open DB
var request = indexedDB.open('macroPlay');
//if fails
request.addEventListener('error', showerror);
//if succeeds
request.addEventListener('success', start);
//if !exist, create.
request.addEventListener('upgradeneeded', createdb);
//Create Admin account on launch
chkAdmin();
}
function createdb(e){
var datababase = e.target.result;
var myusers = datababase.createObjectStore('users', {keyPath: 'userName'});
}
function start(e){
db = e.target.result;
showUsers();// Show all values in the object store
}
function addObject(){
if(confirm('Are you sure you want to resgister?')){
var fName = document.getElementById('fName').value;
var lName = document.getElementById('lName').value;
var userName = document.getElementById('uName').value;
var pass = document.getElementById('password').value;
var email = document.getElementById('email').value;
var dob = document.getElementById('dob').value;
var phone = document.getElementById('phone').value;
var bio = document.getElementById('bio').value;
var nl = document.getElementById('nl').value;
var terms = document.getElementById('terms').value;
var school = document.getElementById('school').value;
//May need to set a loop to find value of radio
var gender;
var radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
gender=radios[i].value;
}
}
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
//Add item
var request = myusers.add(new getUser(userName,fName,lName,pass,email,dob,phone,bio,nl,terms,school,gender));
}
// Show all results.
mytransaction.addEventListener('complete', showUsers);
//Reset Form Fields
resetForm();
}
function getUser(userName, fn, ln, pw, em, dob, tel, bio, nl,tm, scl, gender){
this.userName = userName;
this.fn = fn;
this.ln = ln;
this.pw = pw;
this.em = em;
this.dob = dob;
this.tel = tel;
this.bio = bio;
this.nl = nl;
this.tm = tm;
this.scl = scl;
this.gender = gender;
}
//------Create Admin Account-----//
function chkAdmin(){
alert('before adding admin');
if(localStorage.getItem('admin')!="added"){
alert('adding admin');
addAdmin();
alert('admin added');
}
}
function addAdmin(){
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
var request = myusers.add(new getUser('admin','Shawn','Smith-Choa','admin'));
request.addEventListener('success',showUsers);
//Locally store that admin as been created
var admin = 'admin';
var value = 'added';
newItem(admin,value);
}
//-------------Web Storage API------------//
function newItem(id,style){
localStorage.setItem(id,style);
}

You're not assigning the value of db to anything so it's always undefined. I think you mean to be doing it in the createdb method, but really you should be capturing/assigning it in the start method which the success handler will trigger (I also can't find the start method anywhere)

Related

XSJS getting result from stored procedure in a variable

I have a situation where I pass a session user as a parameter to stored procedure and get a receiver value which I want to get in a variable so I can pass that to other function in xsjs file to send email.
I am getting sender from session user and doing concat to get sender email.
I am calling ReadAuditUser stored procedure will see if the appuser(session user) is valid or not
if ReadAuditUser stored procedure finds appuser as a valid user then stored procedure will return a single record which will return receiver,
if ReadAuditUser stored procedure finds appuser as a invalid user then the stored procedure will return 'null'.
I want to capture that receiver from getReceivername(), like I have capture appuser from getUsername()function.
Please let me know where I am going wrong.
function getUsername() {
var username = $.session.getUsername();
return username;
}
var appuser = getUsername();
var str2 = "#abc.com";
var sender_email = appuser.concat(str2);
function getReceivername() {
var xreceiver = "";
var conn = $.db.getConnection();
var query = 'call \"AA\".\"PROCEDURE::ReadAuditUser\"(?)';
var pstmt = conn.prepareCall(query);
pstmt.setString(1, appuser);
pstmt.execute();
var rs = pstmt.getResultSet();
if (rs.next()) {
if (rs.getString(1) === 'null') {
xreceiver = rs.getString(1);
} else {
xreceiver = rs.getString(1);
}
}
}
rs.close();
pstmt.close();
conn.close();
var receiver = getReceivername();
var str1 = "#abc.com";
var receiver_email = receiver.concat(str1);
function getUsername() {
var username = $.session.getUsername();
return username;
}
var appuser = getUsername();
var str2 = "#abc.com";
var sender_email = appuser.concat(str2);
function getReceivername() {
var xreceiver = "";
var conn = $.db.getConnection();
var query = 'call \"AA\".\"PROCEDURE::ReadAuditUser\"(?)';
var pstmt = conn.prepareCall(query);
pstmt.setString(1, appuser);
pstmt.execute();
var rs = pstmt.getResultSet();
if (rs.next()) {
if (rs.getString(1) === 'null') {
xreceiver = rs.getString(1);
} else {
xreceiver = rs.getString(1);
}
}
return xreceiver; /* have to add this code line and it works*/
}
rs.close();
pstmt.close();
conn.close();
var receiver = getReceivername();
var str1 = "#abc.com";
var receiver_email = receiver.concat(str1);

How to restrict from sending null values into Firebase

I am trying to do a validation in firebase. However, even when I left the field blank and click submit, the null value is still submitted. How do I validate or change any security in a way that it will restrict any null values from saving into the database?
function save() {
window.location = 'profile.html';
var email = firebase.auth().currentUser.email;
var uid = firebase.auth().currentUser.uid;
var name = document.getElementById('name').value
var address = document.getElementById('address').value
var phone = document.getElementById('phone').value
var occupation = document.getElementById('TypeSelect').value
//One of the validation example
var name;
name = document.getElementById("name").value;
if (name == "") {
alert("Please enter your name");
};
var data = {
User_id: uid,
Name: name,
Address: address,
Phone: phone,
Email: email,
Occupation: occupation,
}
var updates = {};
updates['/users/' + uid] = data;
firebase.database().ref().update(updates);
}
A simple way is to only put items in data if they have a value:
var data = {};
if (uid) data.User_id = uid;
if (name) data.Name = name
if (address) data.Address = address;
if (phone) data.Phone = phone;
if (email) data.Email = email;
if (occupation) data.Occupation = occupation;

How to persist data in an array even when the page reloads, using javascript?

I have created a register and a login form using html and javascript. Where I am storing the user data in an array and then in local storage. For this I have initially declared an empty array called var users=[];
Thus, when the page reloads the previously stored data is lost as array becomes empty again and data in the local storage is overwritten. Please help, on how to avoid the array become empty after reloading the page.
Following is my controller.js-
//Declaring an empty array
var users = [];
//Setting id for each users
var idInput = makeCounter();
//Fetching data from textboxes in register.html
var firstnameInput = document.getElementById("firstname");
var lastnameInput = document.getElementById("lastname");
var emailInput = document.getElementById("email");
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");
var dobInput = document.getElementById("dob");
var messageBox = document.getElementById("editeddata");
//Declaring custom constructor function
function userdetails(id, firstname, lastname, email, dob, username, password){
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.dob = dob;
this.username = username;
this.password = password;
this.FullName = this.firstname +' ' + this.lastname;
}
//counter funtion, to fetch user id
function makeCounter() {
var arraylength=users.length;
return function(){
return arraylength+1;
}
}
//insert data while registration
function registerUser()
{
//Email validation
var emailinput = document.forms["myform"]["email"].value;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!(emailinput).match(emailReg) || emailinput=="")
{
alert("Not a valid e-mail address");
return false;
}
//check, if fields are empty
if(firstnameInput.value=="" || lastnameInput.value=="" || passwordInput.value=="" || dobInput.value=="")
{
alert("Fields cannot be empty");
return false;
}
//check, if a user already exist
var usernameinput = document.forms["myform"]["username"].value;
var passwordinput = document.forms["myform"]["password"].value;
var ulen= users.length;
for(i=0; i < ulen; i++)
{
if ( usernameinput == users[i].username && passwordinput == users[i].password)
{
alert("User already exists");
return false;
}
}
var user=new userdetails(idInput(),firstnameInput.value, lastnameInput.value, emailInput.value, dobInput.value, usernameInput.value, passwordInput.value);
users.push(user);
alert("Registered successfully");
localStorage.setItem("key_users", JSON.stringify(users));
}
You can use local storage value at the time of initialisation.
if (typeof(Storage) !== "undefined") {
if (localStorage.key_users) {
users = localStorage.key_users;
} else {
users = [];
}
}
you can use something like this to check if the key is already in localStorage or not.
<html>
<head>
<link href="style.css" rel="stylesheet">
</head>
<body onload="test()">
<script>
function test(){
var value = (localStorage.getItem("key1"))
console.log(value)
if(value == null){
localStorage.setItem("key1","value1")
alert("Hellow")
}else{
var value=localStorage.getItem("key1");
alert(value)
}
}
</script>
</body>
</html>

How to ignore empty fields in Ionic / Firebase?

I have a function for the user to be able to change his own details in his account like his description or social links etc...
However, when I submit the form, it replaces everything and the empty values just erase the field in the database.
Any way to submit the form and replace ONLY the values that have been entered in the field and ignore the empty ones ?
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
var city = cityInput.value;
var age = ageInput.value;
var hobbies = hobbiesInput.value;
var facebook = facebookInput.value;
var twitter = twitterInput.value;
var instagram = instagramInput.value;
var youtube = youtubeInput.value;
var snapchat = snapchatInput.value;
var linkedin = linkedinInput.value;
var email = emailInput.value;
var password = passwordInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
city: city,
age: age,
hobbies: hobbies,
facebook: facebook,
twitter: twitter,
instagram: instagram,
youtube: youtube,
snapchat: snapchat,
linkedin: linkedin,
email: email,
password: password,
});
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
});
var firebase_data = {};
var userID = firebase.auth().currentUser.uid;
var input_data = {
nameInput: document.querySelector('#name'),
descriptionInput: document.querySelector('#description'),
cityInput: document.querySelector('#city'),
ageInput: document.querySelector('#age'),
hobbiesInput: document.querySelector('#hobbies'),
facebookInput: document.querySelector('#facebook'),
twitterInput: document.querySelector('#twitter'),
instagramInput: document.querySelector('#instagram'),
youtubeInput: document.querySelector('#youtube'),
snapchatInput: document.querySelector('#snapchat'),
linkedinInput: document.querySelector('#linkedin'),
emailInput: document.querySelector('#email'),
passwordInput: document.querySelector('#password'),
saveButton: document.querySelector('#save')
}
for(var key in input_data) {
if(input_data.hasOwnProperty(key) && input_data[key].value.length) {
firebase_data[key] = input_data[key].value
}
}
firebase.database().ref('accounts/' + userId).set(firebase_data)
For the people, like me, that are new to this, here is the solution I found : Autocomplete the fields that have a value already so when I submit the form it is saved again with the same value.
The code :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
var database = firebase.database().ref('/accounts/' + userId);
// Retrieve information into the fields already filled in Database
database.on('value', function(snapshot) {
var displayName = snapshot.val().name;
var description = snapshot.val().description;
var displayCity = snapshot.val().city;
var displayAge = snapshot.val().age;
var displayHobbies = snapshot.val().hobbies;
var displayFacebook = snapshot.val().facebook;
var displayTwitter = snapshot.val().twitter;
var displayInstagram = snapshot.val().instagram;
var displayYoutube = snapshot.val().youtube;
var displaySnapchat = snapshot.val().snapchat;
var displayLinkedin = snapshot.val().linkedin;
var displayEmail = snapshot.val().email;
var displayPassword = snapshot.val().password;
$scope.$apply(function() {
$scope.displayName = displayName;
$scope.description = description;
$scope.displayCity = displayCity;
$scope.displayAge = displayAge;
$scope.displayHobbies = displayHobbies;
$scope.displayFacebook = displayFacebook;
$scope.displayTwitter = displayTwitter;
$scope.displayInstagram = displayInstagram;
$scope.displayYoutube = displayYoutube;
$scope.displaySnapchat = displaySnapchat;
$scope.displayLinkedin = displayLinkedin;
$scope.displayEmail = displayEmail;
$scope.displayPassword = displayPassword;
});
document.getElementById("name").value = displayName;
document.getElementById("description").value = description;
document.getElementById("city").value = displayCity;
document.getElementById("age").value = displayAge;
document.getElementById("hobbies").value = displayHobbies;
document.getElementById("facebook").value = displayFacebook;
document.getElementById("twitter").value = displayTwitter;
document.getElementById("instagram").value = displayInstagram;
document.getElementById("youtube").value = displayYoutube;
document.getElementById("snapchat").value = displaySnapchat;
document.getElementById("linkedin").value = displayLinkedin;
document.getElementById("email").value = displayEmail;
document.getElementById("password").value = displayPassword;
});;

Remove localStorage and add it again

I am creating a website that has two languages, English and French. The two languages provides a form that has two steps. What I would like to have happen is, when the user is on English language to refresh the localStorage, so it would not have any information already filled, but load the localStorage (key-value) as empty, from the French forms. Same thing I would like to have happen when the user is in the English language. I know I could use session but I do not to refresh when someone close his browser.
Maybe localStorage.removeItem(''); could help.
Thanks.
Here is my code:
<script type = "text/javascript" > window.onload = getData();
function storeData() {
var userEmail = document.querySelector("#UserName");
var userPhoneNumber = document.querySelector("#PhoneNumber");
var userName = document.querySelector("#FirstName");
var userLastName = document.querySelector("#LastName");
localStorage.setItem("mail", userEmail.value);
localStorage.setItem("phone", userPhoneNumber.value);
localStorage.setItem("name", userName.value);
localStorage.setItem("lastName", userLastName.value);
}
function getData() {
var userEmail = document.querySelector("#UserName");
var userPhoneNumber = document.querySelector("#PhoneNumber");
var userName = document.querySelector("#FirstName");
var userLastName = document.querySelector("#LastName");
userEmail.value = localStorage.getItem("mail");
userPhoneNumber.value = localStorage.getItem("phone");
userName.value = localStorage.getItem("name");
userLastName.value = localStorage.getItem("lastName");
} </script>
Assuming you have a global variable with the current language, you can save it in localStorage in storeData and check if it's the same in getData
function storeData() {
var userEmail = document.querySelector("#UserName");
var userPhoneNumber = document.querySelector("#PhoneNumber");
var userName = document.querySelector("#FirstName");
var userLastName = document.querySelector("#LastName");
localStorage.setItem("mail", userEmail.value);
localStorage.setItem("phone", userPhoneNumber.value);
localStorage.setItem("name", userName.value);
localStorage.setItem("lastName", userLastName.value);
localStorage.setItem("language", currentLanguage);
}
function getData() {
if (localStorage.getItem("language") == currentLanguage) {
var userEmail = document.querySelector("#UserName");
var userPhoneNumber = document.querySelector("#PhoneNumber");
var userName = document.querySelector("#FirstName");
var userLastName = document.querySelector("#LastName");
userEmail.value = localStorage.getItem("mail");
userPhoneNumber.value = localStorage.getItem("phone");
userName.value = localStorage.getItem("name");
userLastName.value = localStorage.getItem("lastName");
}
}

Categories

Resources