Can't pull up user info right after entered in indexedDB - javascript

I have a register form with an indexedDB. I have resgister/log in working. I've been trying different things to get a new register to login as soon as they register but im not sure what's going. It won't work. The localStorage sets like it should but it won't bring up the user's data.
JS:
function addObject(){
if(confirm('Are you sure you want to resgister?')){
fName = document.getElementById('fName').value;
lName = document.getElementById('lName').value;
userName = document.getElementById('uName').value;
pass = document.getElementById('password').value;
email = document.getElementById('email').value;
dob = document.getElementById('dob').value;
tel = document.getElementById('tel').value;
bio = document.getElementById('bio').value;
terms = document.getElementById('terms').value;
school = document.getElementById('school').value;
//Need loop to find radio button values
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.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
}
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}
This is the functions I use when someone logs in.
function loginCheck(user,pass){
db.transaction("users").objectStore("users").get(user).onsuccess = function(e) {
var loggedUser = e.target.result;
if(!loggedUser){
alert('Sorry, Username does not exist. Please try again.');
}else if(pass !== loggedUser.pw ){
alert('Incorrect log in combination. Please try again.');
}else{
loggedIn(loggedUser);
populateFields(loggedUser);
loginStyle(loggedUser)
}
}
}
function loggedIn(loggedUser){
var u=loggedUser;
alert('Welcome '+u.fn+' '+u.ln+' to Macroplay');
//Set localStorage
var signedin = 'user';
var username = u.userName;
newLocal(signedin,username);
}
function getValues(){
db.transaction("users").objectStore("users").get(localStorage.user).onsuccess = function(e) {
populateFields(e.target.result);
loginStyle(e.target.result)
};
;
}
From what I can see the first part adds the user to the DB and the second portion should behave as is I was just logging normally. But it won't pull up the info from the DB.
I've tried setting the new user to localStorage which is how I recognize a user currently loggedin but that also had no effect.
This is my site: http://www3.carleton.ca/clubs/sissa/html5

It looks like you're using the onsuccess handler in the loginCheck method, but you're not when calling put on the db. My guess would be that you're checking to see if the user exists before it's actually had a chance to be added. Try this:
//Add item
var request = myusers.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
request.onsuccess = function () {
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}

Related

My input in the form gets reset when I hit submit . I also tried using console.log() to test if my code is correct but it nothing shows in console

I am creating a form that asks for email and password and validates it. If it has any error, it pops on the same line. Below is my javascript code for it. When I fill the form and hit submit, the values get reset. Moreover, I do not see anything in the console. I tried using a random code console.log('Hanee') to test my code but nothing gets generated in the console tab. Could anyone tell me what's the issue here?
Also, here's the link to my login form: http://www2.cs.uregina.ca/~hsb833/215a/login.html
document.getElementById("login-form").addEventListener("submit",validateLogin,false);
function validateLogin(event){
var elements = event.currentTarget;
var emailValue = elements[0].value;
var passValue = elements[1].value;
checkEmail(emailValue);
checkPass(passValue);
}
function checkEmail(emailValue){
var regex_email = /^[/w]+#[a-zA-Z]+?\.[a-zA-Z]{2,3}$/;
var index = emailValue.search(regex_email);
var errorEmail = document.getElementById("errorEmail");
var valid = true;
console.log('Hanee');
if(index != 0){
errorEmail.style.display = 'inline';
}
}
function checkPass(passValue){
var password = document.getElementById("password");
var regex_pass = /[\w]+\S/;
var index = passValue.search(regex_pass);
if(passValue.length < 6){
console.log('password is invalid. Minimum length is 6');
errorPassLen.style.display = 'inline';
}
if(index != 0){
console.log('password is invalid. Please make sure there is no spaces in between');
errorPassFormat.style.display = 'inline';
}
}
form is refreshed after being submitted by default. To prevent that, use event.preventDefault(); in your validateLogin
Here is an example of a form with a username and password, maybe it will suit you and you can customize it for your needs
async function tebeFxhr() {
let logfil = 1;
let sotebe= false;
let tes =(logt) => {
return /^[a-zA-Z0-9]+$/ui.test(logt);
}
tes(gtebe)==true ? logfil++ : alert('Login cannot contain characters or spaces')
let textrf =(rutext) => {
return /[а-я]/i.test(rutext);
}
textrf(stebe)==true ? alert('The password cannot contain Cyrillic characters') : logfil++;
stebe.length < 8 ? alert('Password is very short') : logfil++;
stebe===ftebe ? logfil++ : alert('Enter the password 2 times so that they match')
if (logfil === 5){
const data = {data_0:gtebe, data_1:stebe, data_2:ftebe};
const response = await fetch("/form", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => {
return response.text();
})
.then((sotebe) => {
console.log(sotebe)
if(sotebe==='error-1'){
console.log('error-1')
}
else{
sotebe =='' ? location.replace("../") : alert(sotebe)
}
});
}
}
When submit event is triggered, all values are sent to server and get reset. If you want to prevent this, use event.preventDefault(); inside the event handling function validateLogin(event). Then, the values are not going to be reset!
Still If you want your values to be empty after submission, try below.
elements.forEach(e => e.value = '');

How can I keep message values in Javascript

I am quite new to Javascript, so I ask for help because somehow I get stuck.
I dont want the input field to become empty after a page refresh - with some copy&paste of code parts I could partially solve it by using sessionStorage + setItem / getItem.
Now I would like the corresponding message also not become empty - at the moment it disappears when I refresh the page. What's the easiest way to get the message? Thank you for your help!
javascript:
let userInput;
let messageUserText;
var validUser = false;
onload = function (event) {
userInput = document.getElementById('usernameInput');
messageUserText = document.getElementById('userMsg');
}
function InputUser() {
const userName = usernameInput.value;
let messageUserName = '';
if (userName === '') {
messageUserName = 'EMPTY';
validUser = false;
} else {
messageUserName = 'OK';
validUser = true;
}
//THIS IS THE MESSAGE I WANT TO KEEP
messageUserText.innerHTML = messageUserName;
}
//KEEP INPUT AFTER SITE REFRESH
document.getElementById("usernameInput").value = getSavedValue("usernameInput");
//SAVE VALUE
function saveValue(e){
var id = e.id;
var val = e.value;
sessionStorage.setItem(id, val);
}
//RETURN SAVED VALUE
function getSavedValue (v){
if (!sessionStorage.getItem(v)) {
return "";
}
return sessionStorage.getItem(v);
}
html:
<body>
<form>
<input type="text" id="usernameInput" oninput="InputUser()" onkeyup="saveValue(this)">
</form>
<!-- THIS IS THE MESSAGE I WANT TO KEEP AFTER REFRESH -->
<div class=""><p id="userMsg"></p></div>
<script src="javascript.js"></script>
</body>
I tried a lot and have partially solved it. Now its able to save the input and associated message to keep them after site refresh.
But I need help to keep the message color and the state of the submit button . I made some tries but cannot get it going. Please can someone tell me how to write the code? I commented it below.
Javascript:
.
.
.
onload = function (event) {
userInput = document.getElementById('usernameInput');
messageUserText = document.getElementById('userMsg');
setPasswordButton = document.getElementById('passwordButton');
}
function InputUser() {
const userName = usernameInput.value;
let messageUserName = '';
if (userName === '') {
messageUserText.style.color = 'red';
messageUserName = 'Message 1';
validUser = false;
} else {
messageUserText.style.color = 'green';
messageUserName = 'Message 2';
validUser = true;
}
messageUserText.innerHTML = messageUserName;
//Save Message to sessionStorage
var idUserMsg = userMsg.id;
var valUserMsg = messageUserText.innerHTML;
sessionStorage.setItem(idUserMsg, valUserMsg);
//Save Message Color (messageUserText.style.color)
//How?
//Button Activation
if (validUser) {
setPasswordButton.disabled = false;
} else {
setPasswordButton.disabled = true;
}
//Save Button state (setPasswordButton.disabled)
//How?
}
//Keep Inputs after site refresh
document.getElementById("usernameInput").value = getSavedValue("usernameInput");
document.getElementById("userMsg").innerHTML = getSavedValue("userMsg");
//Keep Message Color How?
//Keep Button state How?
//Save sessionStorage
function saveValue(e){
var id = e.id;
var val = e.value;
sessionStorage.setItem(id, val);
}
//Return from sessionStorage
function getSavedValue (v){
if (!sessionStorage.getItem(v)) {
return "";
}
return sessionStorage.getItem(v);
}

How to login successfully with details from local Storage [JavaScript]

So basically i store the details entered by the user in the register form into local HTML storage... And i have checked that the details ARE stored in local storage, however, when i try to log in with such information (username and password) in the login form.... it doesn't work. So how would i be able to log in the login form successfully?? In other words, how would i be able to get the data for username and password entered in the register form (which is stored in local storage) and use that to compare with user's input in login form to validate the login process?? Here are files:
You have to compare them to user and pass, not username and password:
var entry = localStorage.getItem("entry");
console.log("username: " + entry.user + "password: " + entry.pas);
if(username.value == entry.user && password.value == entry.pass) {
alert('You have successfully logged in.');
}
In the browser pres CTRL + SHIFT + I, and if it's not open select "Console"
These lines won't work:
var storedUserName = localStorage.getItem('UserName');
var storedPassWord = localStorage.getItem('PassWord');
var storedEmailAddress = localStorage.getItem('EmailAddress');
savedata() doesn't save each field to its own item, it just saves the entry object as a whole. So you need to retrieve that and parse it.
var entryJSON = localStorage.getItem('entry');
if (!entryJSON) {
alert("Nothing stored!");
return;
}
var entry = JSON.parse(entryJSON);
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
To search allEntries, you need to use a loop:
function validlogin(event) {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var entriesJSON = localStorage.getItem('allEntries');
if (!entriesJSON) {
alert("Nothing stored!");
event.preventDefault();
return;
}
var allEntries = JSON.parse(entriesJSON);
for (var i = 0; i < allEntries.length; i++) {
var entry = allEntries[i];
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
if (username == storedUserName && password == storedPassWord) {
alert("Successfully logged in!");
return;
}
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
}

Javascript / jQuery with localStorage API not working

I am trying to use the localStorage API to grab an email value when the user submits a form and then populate another form field later.
I tried using vanilla javascript first:
window.onload = function() {
// Check for LocalStorage support.
if (localStorage) {
// Add an event listener for form submissions
document.getElementById('searchBooking').addEventListener('submit', function() {
// Get the value of the email field.
var email = document.getElementById('email').value;
// Save the email in localStorage.
localStorage.setItem('email', email);
});
}
// Retrieve the users email.
var email = localStorage.getItem('email');
if (email != "undefined" || email != "null") {
document.getElementById('guestEmail').innerHTML = email;
} else {
document.getElementById('guestEmail').innerHTML = "";
}
}
But got this error message in the browser console on line 21:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Then I tried with this jQuery:
$(function() {
// Check for LocalStorage support.
if (localStorage) {
// Add an event listener for form submissions
$('#searchBooking').on('submit', function() {
// Get the value of the email field.
var email = $('#email').value;
// Save the name in localStorage.
localStorage.setItem('#email', email);
});
}
var email = localStorage.getItem('#email');
if (email != "undefined" || email != "null") {
$('#guestEmail').html = email;
}
else {
$('#guestEmail').html = "";
}
});
I didn't get an error message but nothing worked.
Sorry, I am very new to Javascript and don't use it very often, but I really need to save this value and repopulate it in another form.
after looking at your gist link, I found that guestEmail is a textbox on your page so the innerHTML is not going to work here. also the jquery implementation for both .value and .html is not correct.
you need to update your jquery as follows
$(function() {
// Check for LocalStorage support.
if (localStorage) {
// Add an event listener for form submissions
$('form').on('submit', function() {
// Get the value of the email field.
var email = $('#email').val();
// Save the name in localStorage.
localStorage.setItem('#email', email);
$('#guestEmail').html(email);
console.log(localStorage.getItem('#email'));
});
}
var emailLocalStorage = localStorage.getItem('#email');
console.log(emailLocalStorage);
if (typeof emailLocalStorage != "undefined" && emailLocalStorage != "null") {
$('#guestEmail').val(emailLocalStorage);
console.log(emailLocalStorage)
} else {
$('#guestEmail').val("");
}
});
Hope this helps.

Submit fires even if email.value == ""

I'm making a simple form where a user submits a video, alongside their email address. I'd like to make it so that the person can not submit the form until they have filled in the email and saved the video.
The video part is working, but when I test with an empty email, it still seems to submit. The code is below, and the live version is at http://www.atlas-china.com/record-your-multi-lingual-abilties/
Help much appreciated!
// Global variable to hold player's reference.
var _Nimbb;
// Global variable to hold the guid of the recorded video.
var _Guid = "";
// Event: Nimbb Player has been initialized and is ready.
function Nimbb_initCompleted(idPlayer) {
// Get a reference to the player since it was successfully created.
_Nimbb = document[idPlayer];
}
// Event: the video was saved.
function Nimbb_videoSaved(idPlayer) {
_Guid = _Nimbb.getGuid();
}
jQuery(document).ready(function ($) {
// Get the data from the form. Check that everything is completed.
$('#video_submit').click(function (e) {
var email = document.getElementById("email").value;
var video_title = document.getElementById("video_title").value;
var form = document.myForm;
// Make sure the email is specified.
if (email.value == "") {
alert("Please enter your email to proceed.");
return;
}
// Verify that the video is not currently recording.
if (_Nimbb.getState() == "recording") {
alert("The video is being recorded. Please wait.");
return;
}
// Check that video has been recorded.
if (_Guid == "") {
alert("You did not save the video. Click save.");
return;
}
// Set the guid as hidden parameter.
form.guid.value = _Guid;
var dataString = 'email=' + email + '&guid=' + _Guid + '&video_title=' + video_title;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/send.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
}
});
document.forms["myForm"].submit();
});
});
After viewing your live site...
email = "" // Empty string
Whereas
email.value = undefined
Try changing your code to
if (email === "") {
alert("Please enter your email to proceed.");
return;
}
I assume you are doing .value twice by mistake as you have the following line earlier in your code
var email = document.getElementById("email").value;
When you return from that handler function, the browser will proceed to carry out the normal behavior of the "submit" event, which is to submit the form.
You can change your "abort" return statements to
return false;

Categories