Im trying to make a login form and i want that info to be save to my firebase database.
I have written the code but the data doesn't get added to my firebase
Here is the code html code
<input type="password" id="password" placeholder="Ur password" required
style="background-color: white; border: none; top: 55%; left: 41.5%; position: absolute; width: 15%; height: 3%;">
<button id="register" style="position: absolute; left: 48%; color: green; top: 60%; border-radius: 2%; border-color: green;" >Continue</button>
Here is the code i used to connect to firebase
<script src="https://www.gstatic.com/firebasejs/9.1.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.1.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.1.1/firebase-database.js"></script>
and here is the code im using to add the data to firebase:
<script id="main">
const firebaseConfig = {
***The config info is here but i removed it for privacy reasons***
};
const app = initializeApp(firebaseConfig);
var username, password;
function ready (){
username = document.getElementById('username').value;
password = document.getElementById('password').value;
}
document.getElementById('register').onclick = function(){
ready();
firebase.database().ref('user/'+ username).set({
user: username,
pass: password
})
}
Are you sure the function is being triggered? If your button is in a form then it might trigger the default form submission. Also the set() method returns promise so try refactoring the function like this:
document.getElementById('register').onclick = async function() {
// async function ^^^^^
console.log('Register button clicked')
ready();
// add await
await firebase.database().ref('user/'+ username).set({
user: username,
pass: password
})
console.log('Date Added To Firebase')
}
If the button is in a form as mentioned earlier, try setting the type like this:
<button id="register" type="button" ></button>
Related
I made a contact form with JavaScript validation but the validation function does not work. Although it does not show any errors in the console. The submit funtion itself does work and shows an alert box when you submit the form.
The validation function adds a CSS error class and then should show the error message, the error border and the erros symbol. When I add the error class manually to the HTML file the erros signs do show. But with the funtcion it does not.
I think maybe it has to do something with the way how I add the function to the form. But I checked everything and it just seems to look fine.
Who knows what is going wrong?
Some help would be very much appreciated! Thanks in advance!
var firebaseConfig = {
apiKey: " /* anominzed by editor */ ",
authDomain: " /* anominzed by editor */ ",
databaseURL: " /* anominzed by editor */ ",
projectId: " /* anominzed by editor */ ",
storageBucket: " /* anominzed by editor */ ",
messagingSenderId: " /* anominzed by editor */ ",
appId: " /* anominzed by editor */ ",
measurementId: " /* anominzed by editor */ "
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//Reference contactInfo collections
let contactInfo = firebase.database().ref("infos");
// Listen for a submit
document.querySelector(".contactForm").addEventListener("submit",
submitForm);
function submitForm(e) {
e.preventDefault();
checkInputs(); //val
//Get input values
let name = document.querySelector(".name").value;
let email = document.querySelector(".email").value;
let message = document.querySelector(".message").value;
console.log(name, email, message);
saveContactInfo(name, email, message);
//Refresh after submit
document.querySelector(".contactForm").reset();
//Call send email function
sendEmail(name, email, message);
}
const form = document.getElementById('form'); //Val
const namecontact = document.getElementById('namecontact'); //Val
const email = document.getElementById('email'); //Val
const message = document.getElementById('message'); //Val
//form validaton
function checkInputs() {
//Get the values from the inputs
const nameValue = namecontact.value.trim();
const emailValue = email.value.trim();
const messageValue = message.value.trim();
if (nameValue === '') {
setErrorFor(namecontact, "Name cannot be blank");
}
if (emailValue === '') {
setErrorFor(email, "Email cannot be blank");
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid')
}
if (messageValue === '') {
setErrorFor(message, "Message cannot be blank");
}
}
function setErrorFor(input, errorMessage) {
const formControl = input.parentElement; //.form-control
const small = formControl.getElementsByClassName('small');
small.forEach(element => {
small.innerText = errorMessage;
})
//add error message inside small
// add error class
formControl.className = 'form-control error';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
//Save infos to Firebase
function saveContactInfo(name, email, message) {
let newContactInfo = contactInfo.push();
newContactInfo.set({
contactname: name,
email: email,
message: message,
});
}
function showSucces() {
alert("succesfully sent")
}
//Send Email function
function sendEmail(name, email, message) {
Email.send({
Host: "smtp.gmail.com",
Username: "liaraskara#gmail.com",
To: "liaraskara#gmail.com",
From: "liaraskara#gmail.com",
Subject: `${name} sent you a message`,
Body: `Name: ${name} <br/> Email: ${email} <br/> Message: ${message}`,
}).then((message) => showSucces());
}
/* master styles */
html {
height: 100%;
}
.contactForm {
flex: 0%;
margin: 0px 0px;
width: 21%;
position: absolute;
margin: 90px 0px 0px 10.5px;
left: 0px;
/* max-width: 100%; */
/* opacity: 0.39; */
}
.name,
.email,
.subject {
position: relative;
width: 279px;
height: 45px;
padding: 9px 15px 15px 15px;
margin-left: 39.9px;
font-size: 12px;
}
.message {
position: relative;
width: 279px;
height: 141px;
padding: 9px 15px 15px 15px;
margin-left: 39.9px;
font-size: 12px;
}
::placeholder {
margin-top: 0px;
font-size: 12px;
}
.fas.fa-exclamation-circle {
color: red;
width: 15px;
height: 15px;
position: absolute;
visibility: hidden;
top: 15px;
right: 60px;
}
.form-control {
position: relative;
}
.form-control.error input {
border-color: red;
}
.form-control.error i.fas.fas.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.error small {
color: red;
visibility: visible;
}
small {
position: absolute;
left: 66px;
visibility: hidden;
top: 27px;
}
#submitButton {
margin: 9px 0px 0px 42px;
width: 277.2px;
height: 63px;
}
<html lang="en" id="html">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Liara Skara</title>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link rel="stylesheet" href="styles.css">
<!-- <script src='https://kit.fontawesome.com/a076d05399.js'></script> -->
</head>
<body id="bodyContactpage">
<form method="POST" class="contactForm" id="form">
<!-- <div class="backgroundImg" style="background-image: url('Images/LiaraEyesOpen.png');"> -->
<div class="form-control">
<input class="name" id="namecontact" type="text" placeholder="Name" required/><br>
<i class="fas fa-exclamation-circle" id="exclamation1"></i>
<small class="small" id="small1">Error mesagge</small>
</div>
<div class="form-control">
<input class="email" id="email" type="email" placeholder="E-mail" required/><br>
<i class="fas fa-exclamation-circle" id="exclamation2"></i>
<small class="small" id="small2">Error mesagge</small>
</div>
<div class="form-control">
<input class="subject" type="text" placeholder="Subject" /><br>
<i class="fas fa-exclamation-circle" id="exclamation3"></i>
<small class="small" id="small3">Error mesagge</small>
</div>
<div class="form-control">
<textarea class="message" id="message" name="" id="" cols="30" rows="10" placeholder="Message" required></textarea><br>
<i class="fas fa-exclamation-circle" id="exclamation4"></i>
<small class="small" id="small4">Error mesagge</small>
</div>
<button id="submitButton" type="submit">
<span>Launch</span>
<svg class="checkmark" viewBox="0 0 52 52">
<path fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
</svg>
</button>
</form>
<script src="https://smtpjs.com/v3/smtp.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase.js"></script>
<script src="myscript.js">
</script>
</body>
</html>
There are couple of errors in setErrorFor function.
The JavaScript function getElementsByClassName return a
HTMLCollection.
Try converting it to an Array using Array.from(HTMLCollection),
i.e, Array.from(formControl) in your case.
While looping through the Array(formControl) using forEach
function below:
small.forEach(element => { small.innerText = errorMessage; })
you should refer to element and not small. It should be
element.innerText. You also need to set the visibility property for the element with class = 'small'
from hidden to visible.
I had to comment out all the firebase stuff to get your code to run: it was failing to initialise without a complete config, and throwing an error that prevented all the rest of your code from running.
Once I had done that, I found an error in your setErrorFor function:
small.forEach is not a function
This is because getElementsByClassName (and also querySelectorAll) does not return an array, but a HTMLCollection. This doesn't have map or forEach methods.
Instead, you can use:
for (const el of small) {
el.innerText = errorMessage
}
In general, however, my advice would be to add descriptive logging to your code, so you can follow exactly what is happening. You may also wish to enable "Preserve/persist logs" in your browser devtools settings, in case the logs are being cleared by an unexpected page reload.
Thanks for your help! I have solved it and it is working now, by taking the function out of the other submit function. And I changed the setErrorFor function to this;
function setErrorFor(input, errorMessage) {
const formControl = input.parentElement; //.form-control
const small = formControl.querySelector('small');
//add error message inside small
small.innerText = errorMessage;
// add error class
formControl.className = 'form-control error';
}
This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 2 years ago.
I'm trying to create a form that when submitted, creates a new object with the input values, and then stores that object in an array.
For some reason, the array is "resetting" and not saving the objects.
let myLibrary = []
function Book(title,author,pages,read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
myLibrary.push(this)
}
function checkForm(){
let name = document.querySelector('input[name="title"]').value
let author = document.querySelector('input[name="author"]').value
let pages = document.querySelector('input[name="pages"]').value
let read = document.querySelector('input[name="read"]').checked
new Book(name,author,pages,read)
document.getElementById('library').innerText = JSON.stringify(myLibrary)
}
const submit = document.getElementById('btn1')
submit.addEventListener("click",checkForm);
<input name='title' />
<input name='author' />
<input name='pages' />
<input name='read' />
<button id='btn1'>Click me! </button>
<div >Library:</div>
<div id='library'></div>
You are listening for a click event on the submit button, however the submit button also submits the form. Forms will naturally cause a refresh if the default "submit" event is not prevented.
Instead you could listen to your forms submit event and prevent it:
// Query select the form and
form.addEventListener('submit', function(e){
e.preventDefault();
checkForm();
});
As you have a form in your html, you'll have to prevent its default submission event which results in a reload of the page with preventDefault(). You could, for example, change your checkForm() and add the e.preventDefault() there to prevent the form from being submitted.
let myLibrary = []
function Book(title, author, pages, read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
}
function addtoLibrary(title, author, pages, read) {
let book = new Book(title, author, pages, read)
myLibrary.push(book)
}
let table = document.querySelector(".table");
myLibrary.forEach(function(e) {
table.innerHTML += `<tr><td>${e.title}</td>
<td>${e.author}</td>
<td>${e.pages}</td>
<td>${e.read}</td>
</tr>
`
});
// Selectors
let add = document.querySelector("#add")
let submit = document.querySelector("#submit")
function checkForm(e) {
e.preventDefault(); // prevent the form from being submitted
let name = document.querySelector('input[name="title"]').value
let author = document.querySelector('input[name="author"]').value
let pages = document.querySelector('input[name="pages"]').value
let read = document.querySelector('input[name="read"]').checked
addtoLibrary(name, author, pages, read)
console.log(myLibrary);
}
submit.addEventListener("click", checkForm);
html,
body {
height: 100%;
}
* {
font-family: Graphik Regular;
}
ul {
list-style-type: none;
}
table,
th,
td {
border-collapse: collapse;
text-align: left;
border: 1px solid black;
}
table {
width: 100%;
}
td,
th {
height: 50px;
padding: 10px;
width: 200px;
min-width: 100px;
}
th {
background-color: gray;
margin-bottom: 50px;
}
.headers {
margin-bottom: 5px;
}
button {
background-color: #4CAF50;
/* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 30px;
}
.pop-container {
text-align: center;
/* display: none;*/
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
}
form {
background-color: gray;
}
input {
font-size: 20px;
width: 300px;
margin-bottom: 5px;
}
<!DOCTYPE html>
<meta charset="UTF-8">
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</stylesheet>
<script type="text/javascript" src="http://livejs.com/live.js"></script>
</head>
<body>
<div class="pop-container">
<form id="bookquery">
<input type="text" name="title" id="title" placeholder="Title"></br>
<input type="text" name="author" placeholder="Author"></br>
<input type="text" name="pages" placeholder="Pages"></br>
<p>Have you read it?<input type="checkbox" placeholder="Title" name="read"></p>
</br>
<button id="submit">Submit</button>
</form>
</div>
<table class="headers">
<th>Title</th>
<th>Author</th>
<th>Pages</th>
<th>Read</th>
</table>
<table class="table tstyle">
</table>
<button id="add">Add new book</button>
<script src="script.js"></script>
</body>
</html>
function checkForm(e) {
e.preventDefault(); // prevent the form from being submitted
let name = document.querySelector('input[name="title"]').value
let author = document.querySelector('input[name="author"]').value
let pages = document.querySelector('input[name="pages"]').value
let read = document.querySelector('input[name="read"]').checked
addtoLibrary(name, author, pages, read)
}
The above answers didn't quite work for me so here is a simplified, fully working example. As a general guide to getting things like this to work I always try to simplify as much as possible.
index.html
<html>
<header></header>
<body>
<div>
<form id="myForm">
<label for="title">title:</label><br>
<input type="text" id="title" name="title" value="title"><br>
<button id="submit">Submit</button>
</form>
</div>
<script type="text/javascript" src="functions.js"></script>
</body>
</html>
functions.html
let myLibrary = [];
function Book(title) {
this.title = title;
myLibrary.push(this);
}
function checkForm(){
let title = document.querySelector('input[name="title"]').value;
new Book(title);
myLibrary.forEach(function(element) {
console.log(element);
});
}
document.getElementById("myForm").addEventListener(
'submit',
function(e) {
e.preventDefault();
checkForm();
}
);
I'll leave it to you to add back in the other fields on the Book object.
I am not sure because I've tried to illustrate that your code actually stores the object. It's either that your form refreshes the page... that might be the cause but as far as the code you've provided is concerned, everything works as expected.
let myLibrary = []
function Book(title,author,pages,read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
myLibrary.push(this)
}
function checkForm(name,author,pages,read)
{
new Book(name,author,pages,read)
}
checkForm("Chris","Jerry","56","65");
checkForm("Sean","John","56","65");
// Both Objects are still stored...
console.log(myLibrary);
I am using a JavaScript function to check if caps lock is on and on the console window I get "Uncaught TypeError: Cannot read property 'addEventListener' of null
at login.js:41"
In google chrome's console window I also get an error
"The key "intial-scale" is not recognized and ignored"
I tried searching for the causes of this problem and I saw people saying that this may be because the function is executed before the DOM runs so I tried adding window.onload before the function but it didn't fix the issue.
// array of objects to store adminstrators data
var usersObj =[
{
username: "karim",
password: "karim2019"
},
{
username: "nourhan",
password: "noura2019"
},
{
username: "nariman",
password: "nariman2019"
}
]
// function to authenticate login information and proceed to the next page
function getLoginInfo()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for(i = 0; i < usersObj.length; i++)
{
if(username == usersObj[i].username && password == usersObj[i].password)
{
alert("Login successful..");
document.getElementById("loginf").action = "dashboard.html";
return
}
}
alert("Username or password is incorrect!");
document.getElementById("loginf").action = "login.htm";
}
var input = document.getElementById("password");
var text = document.getElementById("text");
input.addEventListener("keyup", window.onload=function(event)
{
if (event.getModifierState("CapsLock"))
{
text.style.visibility = "visible";
}
else
{
text.style.visibility = "hidden"
}
});
.row {
margin-top: 5%;
}
/* Bordered form */
form {
margin-top: 20%;
}
/* Full-width inputs */
input[type=text], input[type=password] {
width: 100%;
padding: 1% 2%;
margin: 1%;
display: inline-block;
border: 1px solid black;
box-sizing: border-box;
}
p{
display: none;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 1% 2%;
margin: 1%;
border: none;
cursor: pointer;
width: 100%;
}
/* Add a hover effect for buttons */
button:hover {
opacity: 0.8;
}
/* Add padding to containers */
.container {
padding: 1.5%;
}
/* The "Forgot password" text */
span.psw {
float: right;
padding-top: 1.5%;
}
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, intial-scale=1 maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="loginstyles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="login.js"></script>
<body>
<div class="row">
<div class="col"></div>
<div class="col">
<form id = "loginf" name="loginf" method="POST">
<div>
<h1>Account Login</h1>
</div>
<div><hr></div>
<div class="container">
<label for="username"><b>Username</b></label>
<input id="username" type="text" placeholder="Enter Username" name="username" required>
<label for="password"><b>Password</b></label>
<input id="password" type="password" placeholder="Enter Password" name="password" required>
<p id="text">WARNING!Caps Lock is ON.</p>
<label>
<input type="checkbox" checked="checked" name="remember">Remember me
</label>
<span class="psw">Forgot Password?</span>
<button onclick="getLoginInfo()" type="submit">Login</button>
</div>
</form>
</div>
<div class="col"></div>
</div>
</body>
</html>
I have fixed the issue by wrapping the eventlistener inside a function that runs when the window loads
// array of objects to store adminstrators data
var usersObj =[
{
username: "karim",
password: "karim2019"
},
{
username: "nourhan",
password: "noura2019"
},
{
username: "nariman",
password: "nariman2019"
}
]
// function to authenticate login information and proceed to the next page
function getLoginInfo()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for(i = 0; i < usersObj.length; i++)
{
if(username == usersObj[i].username && password == usersObj[i].password)
{
alert("Login successful..");
document.getElementById("loginf").action = "dashboard.html";
return
}
}
alert("Username or password is incorrect!");
document.getElementById("loginf").action = "login.htm";
}
window.onload=function()
{
var input = this.document.getElementById("password");
var text = this.document.getElementById("text");
input.addEventListener("keyup", function(event)
{
if(event.getModifierState("CapsLock"))
{
text.style.display = "block";
}
else
{
text.style.display = "none";
}
});
};
I'm trying to set up Firebase authentication with email, but I click on the login button and I get this error:
users.js:15 Uncaught TypeError: Cannot read property 'value' of null
It's also sending me to another page (the home page after hitting the login button). Here is a link to the documentation for how to set up the authentication.
Javascript:
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
//var emailTxt = document.getElementById("emailTxt").value;
//var email = emailTxt.val();
//var password = passwordTxt.val();
$('#login').on("click", function(){
var email = document.getElementById('emailTxt').value;
var password = document.getElementById('passwordTxt').value;
authClient.login("password", {
email: $("#email").val(),
password: $("#password").val(),
rememberMe: $("#rememberCheckbox").val()
});
});
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
alert();
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
HTML:
<?php
//CREATE USER
?>
<!DOCTYPE html>
<html>
<head>
<title>Cheapest Used Tires</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"
integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
crossorigin="anonymous"></script>
</head>
<style>
form {
border: 3px solid #f1f1f1;
}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 40%;
border-radius: 50%;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
}
</style>
</head>
<body>
<h2>Login</h2>
<form action="/CMS/login.php">
<div class="imgcontainer">
<img src="img_avatar2.png" alt="Cheapest Used Tires Admin Logn"
class="avatar">
</div>
<div class="container">
<label><b>Email</b></label>
<input id="emailTxt" type="text"
placeholder="Enter Email" name="email" required>
<label><b>Password</b></label>
<input id="passwordTxt" type="password"
placeholder="Enter Password" name="psw" required>
<button type="submit" id="login">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot
password?
</span>
<span class="psw"> | </span>
<span class="psw">Create
account?
</span>
</div>
</form>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script src="/users.js"></script>
</body>
</html>
The problem raise because you are using undefined arguments such as email and password outside the relevant scope.
You have two options:
use document.getElementById inside callback to retrieve the values. (example 1)
call a function with the values. (example 2)
Note: Declaring the firebase functions calls like you did raise exception because they are called with undefined arguments
$('#login').on("click", function(){
// example 1
var email = document.getElementById('emailTxt').value;
var password = document.getElementById('passwordTxt').value;
// email and password are defined
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
});
// example 2
function createUser(email, password) {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
alert();
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});
function logout() {
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
}
You are moving away from the page before the call returns.
The default behavior of Submit button (when clicked) is to POST the form. You have to prevent that from happening. (because you are posting values throught AJAX)
use event.preventDefault()
$('#login').on("click", function(event){
event.preventDefault();
var email = document.getElementById('emailTxt').value;
var password = document.getElementById('passwordTxt').value;
authClient.login("password", {
email: $("#email").val(),
password: $("#password").val(),
rememberMe: $("#rememberCheckbox").val()
});
I am not getting any error i just created a fiddle with your html and i changed the JavaScript. I can console the value entered by the user.
$('#login').on("click", function(event) {
event.preventDefault();
var email = document.getElementById('emailTxt').value;
var password = document.getElementById('passwordTxt').value;
console.log($("#rememberCheckbox").is(":checked"));
console.log(email);
console.log(password);
authClient.login("password", {
email: email,
password: password,
rememberMe: $("#rememberCheckbox").is(":checked")
});
})
check the fiddle https://jsfiddle.net/suhailsulu/ezzxd1th/2/
Add id to your form tag. Then attach on("submit") event handler. Also, fix ids in JQuery selector in object your are passing to authClient.login.
Problems:
id mismatch at email: $("#email").val() and password: $("#password").val(), they should be email: $("#emailTxt").val() and password: $("#passwordTxt").val()
HTML doesn't contain any checkbox with this id="rememberCheckbox". Add this in your HTML.
On click of Login button, form is getting posted to php page and you are not preventing it. Event handler should be attached to form submit event and add e.preventDefault(), which will prevent redirection(post back).
Please see below:
$('#myForm').on("submit", function(e) {
e.preventDefault();
authClient.login("password", {
email: $("#emailTxt").val(),
password: $("#passwordTxt").val(),
rememberMe: $("#rememberCheckbox").val()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<button type="submit" id="login">Login</button>
</form>
Make sure button is of type="button". The default is type="submit" which means the form will be submitted.
Or better - have a onsubmit listener on the form instead of a click listener on the button. And make sure you prevent the default (submitting the form).
Or just don't use form elements ... Forms are a relic from the days before JavaScript. It's default action is to make a HTTP Get request with the form's data in the query string. You could change the action to "post" and it would make a http post instead, with the form's data in the request body instead of querystring. This was added because query strings has a size limit.
Please follow the below code which I have learned through the Firebase tutorial at the link https://www.youtube.com/watch?v=-OKrloDzGpU
The Logout button is set to be hidden and once the user signs up and logs in the logout button is set to visible in the onAuthStateChanged method.
Here is the below implementation of what you are trying to achieve,
Below is the app.js code what you are trying to acheive in users.js code :
(function(){
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
//Get all the elements
const txtEmail= document.getElementById('txtEmail');
const txtPassword= document.getElementById('txtPassword');
const btnLogin= document.getElementById('btnLogin');
const btnSignUp= document.getElementById('btnSignUp');
const btnLogout= document.getElementById('btnLogout');
//Add the Login Event
btnLogin.addEventListener('click', e=>{
//Get the email and password
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
//Sign in
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
//Add the signup event
btnSignUp.addEventListener('click', e=>{
console.log('in signup now');
//Get the email and password
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
//Sign in
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
btnLogout.addEventListener('click', e=>{
firebase.auth().signOut();
});
//Add a realtime listener
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser)
{
console.log(firebaseUser);
btnLogout.classList.remove('hide');
}
else
{
console.log(firebaseUser);
console.log('not logged in');
btnLogout.classList.add('hide');
}
});
}());
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Login System </title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,500" rel="stylesheet">
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row" style="margin-top:20px">
<div class="col-xs-14 col-sm-11 col-md-11 col-sm-offset-2 col-md-offset-3">
<fieldset>
<br>
<div class="col-md-4">
<h2>Please Sign In </h2>
</div>
<br>
<br>
<br>
<br>
<div class="col-md-4">
<input id="txtEmail" name="Email" type="email" placeholder="Email" class="form-control input-md">
</div>
<br>
<br>
<div class="col-md-4">
<input id="txtPassword" name="Pasword" type="Password" placeholder="Password" class="form-control input-md">
</div>
<br>
<br>
<div class="col-xs-6 col-sm-6 col-md-6">
<button id="btnLogin" class="btn btn-action">
Log in
</button>
<button id="btnSignUp" class="btn btn-secondary">
Sign Up
</button>
<button id="btnLogout" class="btn btn-action hide">
Log Out
</button>
</div>
</fieldset>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
How can I pass values from one html page to another html page javascript
For example:
Page1.html page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>arasu</title>
<style type="text/css">
#popupbox{
margin: 0;
margin-left: 40%;
margin-right: 40%;
margin-top: 50px;
padding-top: 10px;
width: 20%;
height: 150px;
position: absolute;
background: #FBFBF0;
border: solid #000000 2px;
z-index: 9;
font-family: arial;
visibility: hidden;
}
</style>
<script language="JavaScript" type="text/javascript">
function login(showhide){
if(showhide == "show"){
document.getElementById('popupbox').style.visibility="visible";
}else if(showhide == "hide"){
document.getElementById('popupbox').style.visibility="hidden";
}
}
</script>
</head>
<body>
<div >
<form name="login" action="AgaramAnimation.html" method="get">
<center>Username:</center>
<center><input name="username" size="14" /></center>
<center>Password:</center>
<center><input name="password" type="password" size="14" /></center>
<center><input type="submit" name="submit" value="login" /></center>
</form>
</div>
</body>
</html>
here i enter two values user name and password when i click submit button the popup will closed and values pass to another page java script given below .
Page2.html
function gettingvalues()
{
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Data Source="";Initial Catalog="";User ID="";Password="";Provider=""";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("select * from logindetails where username='" **+ username +** "' and password= '" **+ password +** "'", connection);
if (!rs.eof) {
document.getElementById("").innerHTML = ""; }
else {
alert('please enter valid username and password');
}
connection.close;
}
Pls help me..........
Assuming your two pages are on the same domain, you can use localStorage.
Popup.html:
var user = prompt('user name', '');
var password = prompt('password', '');
localStorage.user = user;
localStorage.password = password;
Then back in the main page:
var user = localStorage.user;
var password = localStorage.password;
Note 1: I won't comment on security (other than to say of course don't do it like I've done it above!)
Note 2: localStorage is only about 92% supported: http://caniuse.com/namevalue-storage
You can refer to the window that opened your new window (called the parent window) via window.parent and then execute your javascript using that object.
Here is an example of forcing a parent page to refresh using this: [1]Forcing parent page refresh through javascript
So in your case you could have say variables for username and password in your js like this and you could set them in the popup window like so:
//parent window
username = "";
password = "";
....
//popup window
window.parent.username = enteredUsername;
window.parent.password = enteredPassword;
If Main.html has opened Popup.html with window.open(), then the Popup.html page can have a reference to its opening window (the window of Main.html) using window.opener. It could thus call a setCredentials callback function defined in Main.html using
window.opener.setCredentials(...);
Example:
in Main.html:
// callback function called by the popup
function setCredentials(login, password) {
// do what you want with the login and password
}
in Popup.html
// function called when the form is submitted
function login(login, password) {
window.opener.setCredentials(login, password);
window.close();
}