Javascript / jQuery with localStorage API not working - javascript

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.

Related

Console says onsubmit function doesn't exist for register form, even though it clearly does

So I have a register form, as thus:
<form name="register" action="" method="POST" onsubmit="register()" autocomplete="off">
...
</form>
And I know that every child of this form is functioning.
Then, below in a <script> tag I have my main function which is called when the above form is submitted. And I know that everything outside of the register function is running. However, when I input random values into each field of my form, and press submit, the console shows that the register() function called in the onsubmit attribute of my form does not exist. I can't seem to find the problem here:
//Global Vars
var firebaseConfig = { ...
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
var registerButton = document.querySelector("#registerButton");
//Main Register Function
function register() {
event.preventDefault();
//Locally Global Variables
var fullName = document.forms["register"]["fullName"].value;
var username = document.forms["register"]["username"].value.toLowerCase();
//The MD5 is a way to hash the password, that way the real password is safe and only the hash is used
var password = md5(document.forms["register"]["password"].value);
var serviceProvider = document.forms["register"]["serviceProvider"].value;
//Simple If Statement that adds appropriate email suffix based on Service Provider
if (serviceProvider === "Verizon") {
serviceProvider = "#vtext.com";
} else if (serviceProvider === "ATT") {
serviceProvider = "#txt.att.net";
} else if (serviceProvider === "TMobile") {
serviceProvider = "#tmomail.net";
} else if (serviceProvider === "Sprint") {
serviceProvider = "#messaging.sprintpcs.com";
}
var phoneNumber = document.forms["register"]["phoneNumber"].value + serviceProvider;
var emailAddress = document.forms["register"]["emailAddress"].value;
//Checks The Database If The Username Is Already Taken Or Not
db.collection("Users").where("username", "==", username).get()
.then(function(querySnapshot) {
//Checks Each Individual Result -- If there are no results, than this code will not run
try {
querySnapshot.forEach(function(doc) {
//If any result exists, stop here
if (doc.data()) {
alert("I'm sorry but this username is already taken!! Please Try Another One");
throw "Error";
}
});
} catch (error) {
if (error === "Error") {
return;
}
}
//If not
//Add All Of The User Info To The Database
db.collection("Users").doc(username).set({
fullName: fullName,
username: username,
password: password,
phoneNumber: phoneNumber,
emailAddress: emailAddress,
chatsInvolvedIn: []
})
.then(function() {
//If it succeeds, give user the heads up and then take them to their new homepage
alert("Your account under the username " + username + " has been sucessfully created. You will now be redirected to your homepage.");
//Place Code Underneath to Handle Keeping user Logged In For Present and Future Visits, along with redirecting to a homepage
//Code Goes Here
db.collection("Users").doc(username).get().then(function(doc) {
if (doc.exists) {
localStorage.setItem("loggedIn", JSON.stringify(doc.data()));
}
alert(localStorage.getItem("loggedIn"));
//window.location.replace("index.html");
});
})
.catch(function(error) {
//If it fails, tell user to try again later (we don't care about the error message during production, because it is unlikely after our many tests)
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
})
.catch(function(error) {
//If checking the database originally for duplicate usernames fails, then give the user the same warning as above
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
}
I know that my programming practices above aren't the best. if you could help me out, that would be great, thank you!

Mousedown still submitting form, when it should not

hello i have a login validation form which uses a mix of jquery and ajax to do validations... if the values are ok the form should submit, if the values are not ok then the form should not submit... however in my case the form is submitting even when the values are incorrect ( i am using the mousedown function ) please see below my code..
<form method="post" name="loginform" action="models/login.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" />
<div class="errormsg" id="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" />
<div class="errormsg" id="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class="errormsglast" id="errormsg8"></div>
</form>
jquery and ajax
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password - See Forgot Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
/* ----------------- Stop on Submit */
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
Solution Tried - problem is that when user puts the wrong event that is fine, but if user then puts the correct values, the submit returns false on first time, then second time it returns true... it should return true in first go
<input type="button" name="login" id="login" value="Submit">
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
$('[name=loginform]').submit();
}
});
});
Instead of having a type="submit" button just have a normal button e.g<input type="button" name="login" id="login" value="Submit">. Then when you finished checking the values and happy that it should send then just call:
$('[name=loginform]').submit();
Because what is happening currently is that the form submits when you click on the button, because you are not stopping that event from happening.
If you want to prevent the form from submitting I would suggest either not using that button and initiating the submit yourself like I mentioned above, or alternatively you can use the onsubmit="someFunction()" on the form element way and just return false if it should not submit and return true if it should.
I would say your code suffers from a few issues and some bad practices.
I see you are trying to learn JS so forgive me for not directly solving your issue but to give you some pointers and point you to some best practices.
Logic -
It seems like you are doing a login form. I would say most of this checks should not happen in the client but on the server.
When user signups it might be wise to check user name length on the client as well and prompt the user that he can't use the user name he wants to register with, but during login all the client care is can I login or not.
Security -
You seem to have two serious security issues with your code
You allow to test if an e-mail/user exist or not using 'classes/validatelogin.php?f=1'. in general you should always test the user and password together if they exist and match the user should be able to login, if not the login should fail. you shouldn't notify the user why it fails (if the user name does not exist or if it exist but the password is wrong).
You don't seem to hash passwords in the database. I assume it by limiting the password max length. let the user choose as long password as he wants and hash it using a secure hashing algorithm (I'd suggest bcrypt but google around and find a suitable one). I know you are only learning but this is highly important I think hashing is the first thing you need to learn when handling user logins
Working with the DOM.
You should cache your DOM elements
so instead of calling $('#id') all the time in the main function scope set
var emailInput = $("#user_email2");
function submitForm() {
var email = emailInput.val().toLowerCase();
...
}
You should also probably set the text value of the element and not the html doesn't matter much now but since you are setting text value its good practice and will help you avoid unexpected injections and errors.
Since your using ajax you should not let the form to submit itself even when validation is successful.
Common logic should be packed into functions and reused.
There are many places where your original code can be split into shorter and reusable functions
handle async code better
jQuery supports the Promise API when using ajax requests, I would rather use it. Your original code had a few async calls if you needed to sync between them it would have been painful using plain callbacks (and it is probably what caused you issues in the first place)
Here is a simplified solution using my suggestions -
$(document).ready(function() {
"use strict";
var emailInput = $("#user_email2"),
emailError = $("#errormsg6"),
passwordInput = $("#user_password2"),
passwordError = $("#errormsg7");
function required (value) {
if (value) {
return true;
} else {
return false;
}
//this is just to make the code clear you could use
//`return value ? true : false` or `return !!value`
}
$('form:eq(0)').on('submit', function (e) {
var valid = true,
email = emailInput.val(),
password = passwordInput.val();
e.preventDefault();
if ( !required(email) ) {
emailError.text('Email is required');
valid = false;
}
if ( !required(password) ) {
passwordError.text('Password is required');
valid = false;
}
if ( valid ) {
$.ajax({
method: "POST",
url: "login.php",
data: {
email: email,
password: password
}
}).done(function (data, textStatus, jqXHR) {
//redirect user to main page
}).fail(function (jqXHR, textStatus, errorThrown) {
//show the user the error
})
}
});
});

return false not working in jQuery ajax

I am working on a registration form with jquery ajax. My jQuery Code is as follow :
function validateData()
{
var email = jQuery("#email").val();
var username = jQuery("#username").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var regex = new RegExp(/^\+?[0-9(),.-]+$/);
if(!emailReg.test(email))
{
alert('Please enter valid email');
return false;
}
var agreement = jQuery("#agereement").is(":checked");
if(agreement == false)
{
alert("Please agree with the agreement !!! ");
return false;
}
var pass = jQuery("#password").val();
var repass = jQuery("#repeatpass").val();
if(pass != repass)
{
alert("Password & Repeat Password Should be same");
return false;
}
var FirstData = "email=" + email+"&username="+username;
var url = "ajaxcheck.php";
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
if(data == '')
{
alert("No Problem");
var flag = "true";
}
else{
alert("Username Or Email ID Already Exists");
var flag = "false";
}
}
});
alert(flag);
return flag;
}
</script>
When I submit the form and enters the value of username which is already exists in DB then it alerts the Username Or Email ID Already Exists but submit the form instead of staying on the page. What Should I do if it error comes then it should stay on the page instead of submitting the form
When you write:
var flag = "true";
…
var flag = "false";
…
return flag;
The problem is that "true" and "false" are strings containing the word “true” or “false”. To get the actual boolean values true or false, get rid of the quotes:
var flag = true;
…
var flag = false;
…
return flag;
Event handlers only understand boolean return values, not strings.
Use onsubmit in form tag
<form onsubmit="return validateData();">
....
<input type="submit">
</form>
I'm trying to help you from another angle.
Here is an example on how to do form validation (with bootstrap/php/jquery): http://formvalidation.io/examples/contact-form/
Ajax ".done" happens when you get a successful response from the server and ".fail" happens when sending a request or receiving the response has failed. Assuming you want to check if email exists then you can use something in the lines of:
if(response.IsEmailValid === 'false')
{
$('#alertContainer')
.removeClass('alert-success')
.addClass('alert-warning')
.html('Sorry, email has been taken')
.show()
}
You're setting flag to strings, not boolean values. Try using true and false instead of "true" and "false", both of which are truthy.

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;

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

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();
}

Categories