Getting [Object Object] in local storage - javascript

I am currently busy with a registration form, I got everything set up nicely, however, I am running into 2 local storage issues.
I get the VM6858:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) error
When I click register, something stores in the local storage, but not sure what.
The reason I want to make the information stored in local storage is so that it can be checked when the user signs in on the sign in page.
I am aware PHP is a good combination to do this for server-side, but for now, I am just focusing on storing it on the web browser, this is not being used for people to actually register this is just to practice using local storage in various ways.
HTML
<main>
<div class="heading">
<h1>User Registration</h1>
</div>
<form class="form-container">
<ul>
<li><label for="name">Name</label>
<input class="name" type="text" name="name" required />
</li>
<li><label for="surname">Surname</label>
<input class="surname" type="text" name="surname" required />
</li>
<li><label for="phone">Phone</label>
<input class="phone" type="text" name="phone" />
</li>
<li><label for="email">Email</label>
<input class="email" type="text" name="email" required /></li>
<li><label for="password">Password</label>
<input class="password" type="text" name="password" required /></li>
</ul>
<button class="reg" onclick="validate()">Register</button>
</form>
</main>
JS
//storage key
let STORAGE_KEY ="store-user-reg"
//generate ID
const createId = () =>
`${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;
//get html elements
const formEl = {
id:createId(),
name: document.querySelector(".name"),
surname: document.querySelector(".surname").value,
phone: document.querySelector(".phone").value,
email: document.querySelector(".email").value,
password: document.querySelector(".password").value,
};
//Array for stored registered users
usersArray = JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? [];
//function to set local storage
function store(){
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(usersArray));
}
//register button clicked
function validate() {
let name = formEl.name.value;
let surname = formEl.name.value;
let email = formEl.name.value;
let password = formEl.name.value;
if (!name) {
alert("Please fill in name");
}
if (!surname) {
alert("Please fill in Surname");
}
if (!email) {
alert("Please fill in email");
}
if (!password) {
alert("Please create a password");
}
usersArray.push(formEl);
store();
}
I added screenshots so you can see both errors

You are creating your formEl object on page load, and all the fields will be blank, you need to move your declaration inside of your validate() function to actually populate formEl with the data you want.
The other issue is what Ryan mentioned, I suggest clearing your local storage.
Updating the validate function to:
function validate() {
const formEl = {
id: createId(),
name: document.querySelector(".name").value,
surname: document.querySelector(".surname").value,
phone: document.querySelector(".phone").value,
email: document.querySelector(".email").value,
password: document.querySelector(".password").value,
};
if (!formEl.name) {
alert("Please fill in name");
}
if (!formEl.surname) {
alert("Please fill in Surname");
}
if (!formEl.email) {
alert("Please fill in email");
}
if (!formEl.password) {
alert("Please create a password");
}
usersArray.push(formEl);
store();
}
should also help!

I fixed the issue. This was they issue
let name = formEl.name.value;
let surname = formEl.name.value;
let email = formEl.name.value;
let password = formEl.name.value;
So I updated the code to this
let name = formEl.name;
let surname = formEl.surname;
let email = formEl.email;
let password = formEl.password;
which stopped the 1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>)
only thing left to do now is to figured out why the inputs are seen as empty even though I put in the information

Try clearing your localStorage. Otherwise JSON.parse will continuing parsing that string into '[object Object]'. It looks like in a previous attempt you did not stringify the object before calling setItem, so it got saved as the string '"[object Object]"'. You will need to clear that out in order for it to get reinitialized.
Once clear, your initialization logic should work fine.

Related

Simple Login Form

I am trying to implement a simple login form using JavaScript and HTML. When I submit the form, I want to check the username and password against a list of valid credentials.
If the credentials are valid, I want to redirect the user to the home page. Otherwise, I want to show an error message. I have written the following code, but it is not working as expected. Can someone please help me debug this issue?
<form id="login-form">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('login-form');
const username = document.getElementById('username');
const password = document.getElementById('password');
form.addEventListener('submit', function(event) {
event.preventDefault();
const validCredentials = [
{ username: 'user1', password: 'pass1' },
{ username: 'user2', password: 'pass2' }
];
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
window.location.href = '/home';
} else {
alert('Invalid username or password');
}
}
});
</script>
I am implement a simple login form using JavaScript and HTML.
The expected outcome of the code is that when the user enters a valid username and password and clicks the submit button, they will be redirected to the home page. If the username and password are invalid, an error message should be displayed.
First of all, don't do this if you want to use this code for real users and production web app. It's not a good approach to hardcore users or passwords in a JavaScript script. If you are using this code for learning purposes, it's okay!
Secondly, the code has two meaningful problems. The alert inside the else block is running after every iteration of the for loop. You have to add a return statement to stop the loop and exists the function. Place the alert after the for loop, because the intention of the alert (I guess) is: if you don't find any coincidence, show to the user that the username and password are invalid.
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
return window.location.href = '/home';
}
} //end of the loop
alert('Invalid username or password');
}); //end of the callback function
});
On the other hand, in window.location.href = '/home', the string is a malformed URI. You have to send user to a completed URI like, https://google.com/ or http:/yoursite.com/home

displaying string in html after js executes something

So, im trying to create a accounts system, i made a login system that works, but when you enter wrong credentials i want it to display "wrong username or password" in the value of ab empty tag, the thing is that i dont know how to access the tag from app.js (node.js project)
<div class="form">
<form class="login-form" action="/account" method="post">
<p id = "check"></p>
<h1 id = "login-text">Login</h1>
<label style="color:white;">Username:</label>
<input type="text" id = "username" placeholder="Enter Username" name="username" required>
<label style="color:white;">Password:</label>
<input type="password" id = "password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
<h5>register</h5>
</form>
</div>
</div>
app.post('/account', (req, res) => {
const username = req.body.username;
const password = req.body.password;
con.query("USE discbin")
con.query('SELECT * FROM accounts WHERE username = ?', [username], function (err, result, fields) {
if (err) throw err;
if (result.length > 0 && result[0].password === password) {
console.log(result[0].username + " logged in!")
res.render('account');
}
else {
console.log("a user tried to login using the username: " + username)
//set <p> to "wrong username or password"
}
});
});
document.getElementById("check").textContent = "wrong username or password";
Get the element you want to update document.getElementById("check")
Set its textContent property to the text you want to use
I think this is an XY problem.
As far as I know, it is not possible to access a DOM element directly from the server, however, you can achieve the same result with a little JavaScript on the client side.
For example the server response could be on authentication success a JSON object like that:
{
auth: true,
//some token I guess...
}
and on authentication fail:
{ auth: false }
Then, you can use JavaScript to access the element you want and modify its content using the innerHTML method.
In your case, you could store the string to be displayed and modify it according to the server response.
let checkStringVariable = "";
On server response:
checkStringVariable = response.auth ? "" : "wrong username or password";
document.getElementbById("check").innerHTML = checkStringVariable;

JavaScript Login Form Not Validating

Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation

JavaScript A variable assigning itself to itself is causing problems in my code when I run it

I am working on an assignment for class, and the instructor has informed us, here is a book, here is a website, I want you to do this by this date and if you fail its not my fault. I have looked in the website, the book, and several places on stackOverflow but I don't think I've seen a problem like this come up that's been explained well enough for me to troubleshoot my way out of it in time for the turn in on Wednesday at noon (UTC -5).
I have a mockup of a registration form as an HTML page (not even HTML5, please don't ask) Here is the code for that.
function bucc_registration()
{
//THE FOLLOWING ALERT IS FOR TROUBLESHOOTING PURPOSES ONLY
//alert("inside BucC_Registration()");
//GET THE VALUES FROM THE FORM AND STORE IN THE VARIABLES FOR VALIDATION
var fullName = document.getElementById("buccFName").value;
var eMail = document.getElementById("buccEMail").value;
var phone = document.getElementById("buccPhone").value;
var pass = document.getElementById("buccPass").value;
var passConf = document.getElementById("buccPassConf").value;
//CLEAR OUT ALL OLD MESSAGES AND ERRORS
document.getElementById("error1").innerHTML = "";
document.getElementById("error2").innerHTML = "";
document.getElementById("error3").innerHTML = "";
document.getElementById("error4").innerHTML = "";
document.getElementById("error5").innerHTML = "";
document.getElementById("feedback").innerHTML = "";
//CHECK ALL VALUES FOR NON-BLANK ENTRIES
if (fullName == "" || fullName == null || fullName == fullName)
{
document.getElementById("error1").innerHTML = "Please insert your full name.";
return false;
}
//ONCE THEY BYPASS THE INPUT TEST, THEN THE VALIDATION TESTS CAN BEGIN
//fullName NEEDS NO FURTHER VALIDATION
//eMail NEEDS NO FURTHER VALIDATION
//VALIDATION FOR PHONE NUMBER TO MAKE SURE IT WAS ENTERED IN THE XXX-XXX-XXXX FORMAT AND AS NUMBERS
return false;
}
<section>
<form id="frm1" onsubmit="return bucc_registration()" action="">
<input type="text" name="buccFName" id="buccFName" /> Full Name <font color="red"><b id="error1"> </b></font><br />
<input type="text" name="buccEMail" id="buccEMail" /> Email <font color="red"><b id="error2"> </b></font><br />
<input type="text" name="buccPhone" id="buccPhone" placeholder="XXX-XXX-XXXX" /> Phone <font color="red"><b id="error3"> </b></font><br />
<input type="text" name="buccPass" id="buccPass" /> Password <font color="red"><b id="error4"> </b></font><br />
<input type="text" name="buccPassConf" id="buccPassConf" /> Password Confirmation <font color="red"><b id="error5"> </b></font><br />
<input type="submit" name="reset" value="Submit"> <input type="reset" name="reset">
</form>
<script src="scripts/BucC_Registration.js" type="text/javascript"></script>
My problem is that when I run the full code in any browser the JavaScript will fill the variables with blank or user data as it is supposed to. I tried to leave the user name blank to make sure that the error message would show up properly and that's when trouble started. It would error out and when I looked into why it wasn't displaying an error it would tell me it was because the variable was holding a value. Essentially var fullName === fullName; (Yes I did check that, it did work)
I don't know why or how. But I'm fairly certain that once I get this sorted out the other 4 variables that are doing this to me (eMail, pass, and passConf) will stop being a problem.
The current problem is this. How do I stop a variable from becoming its own... content? Its almost as if its shadowing and I'm unable to get it to stop on 4 different variables and I didn't do it intentionally.

How to create a condition to assign admin role to a new user on meteor?

So I'm playing around with meteor. I've created a simple app and added alanning:roles package to be able to have different user roles.
I have this page in my admin environment to create a new user, and I want to add a checkbox to assign a user role to the user before creating. The template html (create-user.html) looks like this:
<template name="AdminCreateUser">
<body>
{{> _adminNav }}
<section class="container main">
<h1>Hmmm...trying to create a user?</h1>
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="registerEmail" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="registerPassword" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" {{checked}} class="toggle-checked"> This is an admin
</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</section>
</body>
</template>
The page JS (create-user.js) is something like this:
Template.AdminCreateUser.events({
'submit form': function(event) {
event.preventDefault();
var emailVar = event.target.registerEmail.value;
var passwordVar = event.target.registerPassword.value;
Accounts.createUser({
email: emailVar,
password: passwordVar
});
}
});
How can I make this checkbox to change the user role for the user that I am creating? I was thinking on making an IF statement to check if it's checked. But I'm having doubts on how/where to create that if statement and where to place the user role in the JS code.
BTW: all this code is in my CLIENT/views/admin folder. Is it there where they're supposed to be?
Thanks guys.
Check out the official documentation here: http://docs.meteor.com/#/full/accounts_passwords
Put a callback inside your createUser function call. Your code on client side is fine as it also directly logs the user in on successful creation of the account. You can then use the profile attribute of currentUser to set your own custom roles. In this case check how alanning:roles defines those.
You can create an if statement checking the value of your checkbox and if checked setting the role like this for example if you would use the regular profile to set a role.
currentUser.profile.role = 'admin';
I had a look and found that with your package this function call can be made after a successful createUser call:
if(user.roles.length > 0){
// Need _id of existing user record so this call must come
// after `Accounts.createUser` or `Accounts.onCreate`
Roles.addUsersToRoles(id, user.roles, 'default-group');
}
More examples and documentation: https://github.com/alanning/meteor-roles
We need to findout if the checked button retrieve true/false value from checkbox I didnt tested these but try to put log if variable X if there's any value. If true or check it can create Admin but false it can create Normal User
Template.AdminCreateUser.events({
'submit form': function(event) {
event.preventDefault();
var emailVar = event.target.registerEmail.value;
var passwordVar = event.target.registerPassword.value;
var x = $(event.target).is(":checked").val();
if(x){
id = Accounts.createUser({
email: emailVar,
password: passwordVar
});
Roles.addUsersToRoles(id, ['admin'], 'default-group');
}else{
id = Accounts.createUser({
email: emailVar,
password: passwordVar
});
Roles.addUsersToRoles(id, ['user'], 'default-group');
}
});
Note: I didn't tested these code but i think i can help you.

Categories

Resources