In my JavaScript Firebase application, I have tried to set up user authentication via email, and at the same time sync user data to Firebase's realtime database. While our Google sign in worked with no problems, the function that makes accounts, firebase.auth().createUserWithEmailAndPassword(email, password); fails to execute and (annoyingly) does not throw any error messages. Here is the code:
main.js: (The problematic section is submitAcc())
var config = {
apiKey: "censored",
authDomain: "censored",
databaseURL: "censored",
projectId: "censored",
storageBucket: "censored",
messagingSenderId: "censored"
};
firebase.initializeApp(config);
var database = firebase.database();
function showAccCreate() { //Hides and shows account create button
var x = document.getElementById("hiddenaccountcreation");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function submitAcc() { //On submit button pressed
alert("Signing in");
var email = document.getElementById("emailinput").value;
var password = document.getElementById("passinput").value;
var username = document.getElementById("usernameinput").value;
//console.log(email + password +username);
var user;
alert("recorded values");
firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(email,password).then(function(result) {
alert("Gets into .then");
var user = firebase.auth().currentUser;
var uidvalue = user.uid;
console.log(uidvalue);
console.log(uidvalue);
alert("User value recorded");
writeUserDataFromEmailSignin(email, username,uidvalue);
alert(user.uid);
}).catch(function(error) {
alert(error.message);
console.log(error.message);
console.log(error.code);
});
}
//Testing if auth state changes
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
alert("User is signed in.");
document.getElementById("debugtest").innerHTML = "Signed in";
}
});
function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
alert("Entered function");
database.ref('users/' + uuid).set({
"name": name,
"email": email,
"uid": uuid,
}).then(function() {
alert("Completed");
}).catch(function() {
console.log(error.message);
console.log(error.code);
})
}
function showsignin() {
var x = document.getElementById("hiddensignin");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function googlesignin() { //Signs people into app via Google
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope("https://www.googleapis.com/auth/contacts.readonly");
firebase.auth().languageCode = 'en';
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken; //Google Auth access token
var user = result.user; //Contains all user info that Google provided us
writeToDatabaseFromGoogle(user.email, user.displayName, user.uid, user.photoUrl);
}).catch(function(error) {
console.log(error.message);
console.log(error.code);
});
}
function writeToDatabaseFromGoogle(email, name, uuid, image_url) { //Writes user data to database from Google signin
database.ref("users/" + uuid).set({
"name": name,
"email": email,
//"imageUrl": image_url,
"uid": uuid,
}).catch(function(error) {
console.log(error.message);
console.log(error.code);
});
}
function signInUser() { //Uses email sign-in so signin to existing account
var email = document.getElementById("emailreauth");
var pass = document.getElementById("passreauth");
// noinspection JSUnresolvedFunction
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
//Handle errors here
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
and the index.html file:
<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAhglAXFWaJhtvOrfeugAMgJHrBw5CUNEc",
authDomain: "projectcrosscomm.firebaseapp.com",
databaseURL: "https://projectcrosscomm.firebaseio.com",
projectId: "projectcrosscomm",
storageBucket: "projectcrosscomm.appspot.com",
messagingSenderId: "412861101382"
};
firebase.initializeApp(config);
</script>
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-database.js"></script>
<!-- Comment out (or don't include) services that you don't want to use -->
<!-- <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-storage.js"></script> -->
<script src="main.js" rel="script"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Cross Comm!</title>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
<button id="showsignin" onclick="showsignin()">Already have an account?</button>
<button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>
<h1>Project Cross Comm!</h1>
<h2 id="subtitle">
Welcome to <strong>Project Cross Comm!</strong>
</h2>
<img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
<h2></h2>
<p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
<div id="hiddenaccountcreation">
<form>
<fieldset>
<legend>Account Creation</legend> <!--Create account via email sign-in-->
<p>
<label for="usernameinput">Username</label>
<input type="text" id="usernameinput" name="createUsername" placeholder="Username">
<p>
<label for="emailinput">Email</label>
<input type="email" id="emailinput" value="" placeholder="example#example.com" name="createEmail">
</p>
<p>
<label for="passinput">Password</label>
<input type="password" id="passinput" value="" placeholder="password" name="createPass">
</p>
<button id="submit" onclick="submitAcc()">SUBMIT</button>
</fieldset>
</form>
</div>
<div id="hiddensignin">
<form>
<fieldset>
<legend>Sign In</legend>
<p>
<label for="usernamereauth">Username</label>
<input type="text" id="usernamereauth" value="">
<p>
<label for="emailreauth">Email</label>
<input type="email" id="emailreauth" value="">
</p>
<p>
<label for="passreauth">Password</label>
<input type="password" id="passreauth" value="">
</p>
<button id="signin" onclick="signInUser()">SUBMIT</button>
</fieldset>
</form>
</div>
<div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
<a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
<h6></h6>
<a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
<h6></h6>
<a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>
</div>
</body>
<footer>
<p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
<noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
</footer>
</html>
The farthest alert my program gets to is alert("recorded values");, no further alerts are executed. Javascript does not throw any errors during the process; the console is empty. Is there any way to find out what's wrong, or even to force Javascript to be more verbose and log its memory every so often?
Can you please try this? This works in my case.
firebase.auth().signInWithEmailAndPassword(email, password)
.then(response => {
const uid = response.user.uid; // you have uid
response.user.getIdToken()
.then(token => {
// do anything with token
})
.catch(error => {
// any error handling
})
})
.catch(error => {
// any error handling
})
Your Current issue is you are not able to store the Values into the DB with the method submitAcc().This method is called when the user creates the account. I have corrected and made some changes please test and let me know if that works for you.
I have added two functions logout() and status() to understand where the problem is. I'd suggest you remove them.
I have also observed in the method signInUser(). You have missed the .value to Email and Password and corrected it.
See below image once the user clicks to Create the Account.I have logged his input to console.
Database Saving user's info:
Code
var database = firebase.database();
function showAccCreate() { //Hides and shows account create button
var x = document.getElementById("hiddenaccountcreation");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function submitAcc() { //On submit button pressed
alert("Signing in");
var email = document.getElementById("emailinput").value;
var password = document.getElementById("passinput").value;
var username = document.getElementById("usernameinput").value;
console.log(email + password +username);
alert("recorded values");
firebase.auth().createUserWithEmailAndPassword(email,password).then(function(result) {
alert("Gets into .then");
var user = firebase.auth().currentUser;
var uidvalue = user.uid;
console.log(uidvalue);
console.log(uidvalue);
alert("User value recorded");
writeUserDataFromEmailSignin(email, username,uidvalue);
alert(user.uid);
}).catch(function(error) {
alert(error.message);
console.log(error.message);
console.log(error.code);
});
}
function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
alert("Entered function");
database.ref('users/' + uuid).set({
"name": name,
"email": email,
"uid": uuid,
}).then(function() {
alert("Completed");
}).catch(function() {
console.log(error.message);
console.log(error.code);
})
}
function logout()
{
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
}
function status()
{
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var emailv =user.email;
console.log("User is signed in. em ankunav enti "+ emailv);
} else {
console.log("No user is signed in.");
}
});
}
//Testing if auth state changes
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
alert("User is signed in.");
document.getElementById("debugtest").innerHTML = "Signed in";
}
else
{
document.getElementById("debugtest").innerHTML = "NOT LOGGED IN ";
}
});
function showsignin() {
var x = document.getElementById("hiddensignin");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function signInUser() { //Uses email sign-in so signin to existing account
var email = document.getElementById("emailreauth").value;
var pass = document.getElementById("passreauth").value;
// noinspection JSUnresolvedFunction
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
//Handle errors here
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "hmcalreac",
authDomain: "kbckyc",
databaseURL: "https://abc.dmc",
projectId: "test12d",
storageBucket: "t11",
messagingSenderId: "11"
};
firebase.initializeApp(config);
</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Cross Comm!</title>
</head>
<body>
<button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
<button id="showsignin" onclick="showsignin()">Already have an account?</button>
<button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>
<h1>Project Cross Comm!</h1>
<h2 id="subtitle">
Welcome to <strong>Project Cross Comm!</strong>
</h2>
<img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
<h2></h2>
<p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
<div id="hiddenaccountcreation">
<fieldset>
<legend>Account Creation</legend> <!--Create account via email sign-in-->
<p>
<label for="usernameinput">Username</label>
<input type="text" id="usernameinput" name="createUsername" placeholder="Username">
<p>
<label for="emailinput">Email</label>
<input type="email" id="emailinput" value="" placeholder="example#example.com" name="createEmail">
</p>
<p>
<label for="passinput">Password</label>
<input type="password" id="passinput" value="" placeholder="password" name="createPass">
</p>
<button id="submit" onclick="submitAcc()">SUBMIT TO CREATE ACCOUNT </button>
</fieldset>
</div>
<div id="hiddensignin">
<fieldset>
<legend>Sign In</legend>
<p>
<label for="usernamereauth">Username</label>
<input type="text" id="usernamereauth" value="">
<p>
<label for="emailreauth">Email</label>
<input type="email" id="emailreauth" value="">
</p>
<p>
<label for="passreauth">Password</label>
<input type="password" id="passreauth" value="">
</p>
<button id="signin" onclick="signInUser()">SUBMIT To Signin to console</button>
</fieldset>
</div>
<button id=mystat onclick="status()">CLICK me to GET Status</button>
<button id=mystat onclick="logout()">CLICK me to logout </button>
<div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
<a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
<h6></h6>
<a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
<h6></h6>
<a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>
</div>
<script src="ne2.js" rel="script"></script>
</body>
<footer>
<p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
<noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
</footer>
</html>
Related
I am using Stripe to accept donations on my website and everything works great but it doesn't save the customer name and email however I am passing it in the billing_details. I think I need to pass it also on the server side,but it gives me this error (Undefined array key "email") when I used the post method '$email=$_POST['email'].. my question is how to pass the email to 'receipt_email' correctly.
\Stripe\Stripe::setApiKey('my secret key');
if(!isset($_SESSION['amount'])){
header("Location: donations.php");
}
$amount = $_SESSION['amount'];
$donation = $amount * 100;
$email = $_POST['email'];
$customer = \Stripe\Customer::create(array(
'email' => $email
));
$intent = \Stripe\PaymentIntent::create([
'amount' => $donation,
'currency' => 'usd',
// Verify your integration in this guide by including this parameter
'metadata' => ['integration_check' => 'accept_a_payment'],
'automatic_payment_methods' => ['enabled' => true],
'customer' => $customer->id,
'receipt_email' => $email,
]);
?>
<!DOCTYPE html >
<html >
<head>
<body>
<form id="payment-form" data-secret="<?= $intent->client_secret ?>">
<label>Card Holder Name</label>
<span id="card-holder-name-info" class="info"></span><br>
<input type="text" id="fullname" name="fullname" required><br>
<label>Email</label>
<span id="email-info" class="info"></span><br>
<input type="email" id="email" name="email" required><br>
<label>Card Number</label>
<div id="card-element" >
<!-- Elements will create input elements here -->
</div>
<button type="submit" id="card-button" class="donate-btn yellow-btn">Donate</button>
</form>
</div>
</div>
<script>
var stripe = Stripe('my public key');
var elements = stripe.elements();
var style = {
base: {
color: "#565556",
}
};
var card = elements.create("card", { style: style });
card.mount("#card-element");
card.on('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
var form = document.getElementById('payment-form');
var fullname = document.getElementById('fullname');
var email = document.getElementById('email');
form.addEventListener('submit', function(ev) {
ev.preventDefault();
stripe.confirmCardPayment(form.dataset.secret, {
payment_method: {
card: card,
billing_details: {
name: fullname,
email: email
}
}
}).then(function(result) {
if (result.error) {
// Show error to your customer (e.g., insufficient funds)
alert(result.error.message);
} else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
// Show a success message to your customer
alert('The payment has been proccessed');
window.location.replace("SuccessPage");
}
}
});
});
</script>
I'm having trouble sending data to the server using a form. I already made a register form that works just fine, and for the most part my client side javascript for the login form is very similar to the javascript for the register form, and I just can't figure out why it won't work. It just gives me "Cannot POST /login.html"
Here's the login form html:
<div class="loginTitle">
<h1>Login</h1>
</div>
<div class="loginFormLayout">
<form method=post id="loginForm">
<div class="loginFormText">
<label for="username">Username</label>
</div>
<div class="loginFormEntry">
<input type="text" placeholder="Enter Username" name="loginUsername" required>
</div>
<div class="loginFormText">
<label for="password">Password</label>
</div>
<div class="loginFormEntry">
<input type="password" placeholder="Enter Password" name=loginPassword required>
</div>
<button type="submit" class="loginButton">Log In</button>
</form>
</div>
And here's the client side javascript:
//Login as an existing user
const login = document.getElementsByClassName('loginButton');
const loginForm = document.getElementById('loginForm');
const loginURL = 'http://localhost:3000/loginUser';
loginForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(loginForm);
let username = formData.get('loginUsername');
let password = formData.get('loginPassword');
loginForm.reset();
let user = { //Create a user object that will be sent to the backend and compared to the user database
username,
password
};
fetch(loginURL, { //Send the user object to the backend in JSON format to be checked against the database
method: 'POST',
body: JSON.stringify(user),
headers: {
'content-type': 'application/json'
}
})});
And the server side javascript for now, console logs are just to see if the info is getting up to the server
app.post('/loginUser', (req, res) => {
console.log(req.body.username);
console.log(req.body.password);
});
EDIT: I've also decided to post the info for my register form, which DOES work and uses similar logic to the login form. Maybe I'm missing something that isn't in the login logic
Register form html:
<div class="loginMenu">
<div class="loginTitle">
<h1>Register</h1>
</div>
<div id="registerWarning"></div>
<div class="loginFormLayout">
<form method="post" id="registerForm">
<div class="loginFormText">
<label for="username" id="newUsername">Username</label>
</div>
<div class="loginFormEntry">
<input type="text" placeholder="Create Username" name="username" required>
</div>
<div class="loginFormText">
<label for="password" id="newPassword">Password</label>
</div>
<div class="loginFormEntry">
<input type="password" placeholder="Create Password" name=password required>
</div>
<div class="loginFormText">
<label for="confirmPassword">Confirm Password</label>
</div>
<div class="loginFormEntry">
<input type="password" placeholder="Confirm Password" name="confirmPassword" required>
</div>
<button type="submit" class="registerButton">Register</button>
</form>
</div>
</div>
Register form client side javascript:
//Register a new user
const register = document.getElementsByClassName('registerButton');
const registerForm = document.getElementById('registerForm');
const registerURL = 'http://localhost:3000/createNewUser';
//When the user presses the register button, get the info from the form
registerForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(registerForm);
let newUsername = formData.get('username');
let newPassword = formData.get('password');
let confirmPassword = formData.get('confirmPassword')
registerForm.reset();
//Make sure new password and confirm password are equal
if (newPassword == confirmPassword) {
if (newUsername != "" && newPassword != ""){ //Make sure user enters something for both fields
let newUser = { //Create an object to send to the back end
newUsername,
newPassword
};
fetch(registerURL, { //Send the newUser object to the backend in JSON format to be added to the database
method: 'POST',
body: JSON.stringify(newUser),
headers: {
'content-type': 'application/json'
}
});
}
}
else { //If newPassword and confirmPassword are not equal, ask the user to enter them correctly
const registerWarning = document.getElementById('registerWarning');
registerWarning.innerText = 'Password and Confirm Password do not match';
registerWarning.style.padding = "10px";
registerWarning.style.background = 'red';
};
});
Register form server-side javascript:
app.post('/createNewUser', (req, res) => {
let newUsername = req.body.newUsername;
let newPassword = req.body.newPassword;
let newUserData = 'INSERT INTO users (username, password) VALUES (?, ?)';//Use the question marks as placeholders
//Use bcrypt to hash the password before putting it in the database
bcrypt.hash(newPassword, saltRounds, function(err, hash) {
db.query(newUserData, [newUsername, hash], function(err, result) {
if (err) throw err;
console.log('New user registered');
});
});
});
I figured it out, thanks to #Rocky Sims for the help.
Basically, the register form doesn't exist on the login html page, which was throwing an error up about how that doesn't exist before it could even get to the login code. So I just had to make seperate register.js and login.js files, as the issue was due to them being in the same file.
Try wrapping your form method (post) in quotes ('') like so <form method='post' id="loginForm">
Also the value for the name attribute for your password input should by in quotes. Like so <input type="password" placeholder="Enter Password" name='password' required>
I think the problem is that you haven't told the server what to send back to the client when the POST /loginUser endpoint gets called. Try adding res.sendStatus(200); at the end of your POST /loginUser handler function (so right after console.log(req.body.password);).
Send Email Directly From JavaScript using EmailJS.
Please look the below answer and I'm getting so many comments for malicious attacks.. because this file is loading in browser so malicious user can easily get your key configuration. So, how to avoid it?
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
Hi you can directly send email through using EmailJS without using the server side code. It'll totally client side.
For sending you need to configure below details.
1)First,Go to this site [https://www.emailjs.com/] and create free account.
2)below 'Connect your email service' button click and configure. You'll get 'YOUR_SERVICE_ID'
3)Then 'Create email template' button click and configure. You'll get 'YOUR_TEMPLATE_ID'
4)click on 'Send email from JavaScript' button. You'll get code.
5)You'll get the 'YOUR_USER_ID' in [https://dashboard.emailjs.com/account]
I did all configuration and added code please check. below code.
NOTE : - "Please encrypted or embedded your use_id for malicious attacks."
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("YOUR_USER_ID"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>
Using JavaScript can expose your credentials like user id , service id to the public. For this , you can store these keys values in a variable (half value) and then manipulating it in runtime like appending remaining half of the key etc. But its not totally safe.
Code :
<html>
<head>
<title>Contact Us</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
</head>
<body>
<div class="container">
<div class="card col-md-6 offset-md-3" style="margin-top:50px;">
<div class="card-body">
<h2>Contact Us</h2>
<label for="thename">Name</label>
<input type="text" class="form-control" id="thename" placeholder="Enter Name">
<label for="themail">Email:</label>
<input type="email" class="form-control" id="themail" placeholder="Enter Email">
<label for="themsg">Message</label>
<textarea class="form-control" id="themsg" placeholder="Enter Message"></textarea>
<button class="btn btn-danger btn-sm" style="margin-top:10px;" onCLick="sendemail();">Send</button>
</form>
</div>
</div>
</div>
<script>
function sendemail() {
var userid = "YourUserID"
emailjs.init(userid);
var thename = document.getElementById('thename').value;
var themail = document.getElementById('themail').value;
var themsg = document.getElementById('themsg').value;
var validmail = /^w+([.-]?w+)*#w+([.-]?w+)*(.w{2,3})+$/;
if (thename == "") {
alert("Please Enter Name");
}
else if (themail == "" || themail.match(!validmail)) {
alert("Please Enter Valid Email");
}
else if (themsg == "") {
alert("Please Enter Message");
}
else {
var contactdetail = {
from_name: thename,
from_email: themail,
message: themsg
};
emailjs.send('YourServiceID', 'YourTemplateID', contactdetail).then(function (res) {
alert("Email Sent Successfully");
},
reason => {
alert("Error Occur");
})
}
}
</script>
</body>
</html>
Make sure to replace "YourUserID" , "YourServiceID" & "YourTemplateID" with your own ids
Reference : Narendra Dwivedi - Send Email From JavaScript
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("service_ud48moz"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('service_ud48moz', 'template_njhhxon', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>
User is not getting created ! The same code works on another sample file I got from youtube , but when I copied and used in my code , it is not working. The user is successfully created in my database with my init-details on that sample file,so I dont think the problem is with my firebase , its somewhere here i think.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var user = firebase.auth().currentUser;
if(user != null){
}
} else {
// No user is signed in.
}
});
function login(){
var userEmail = document.getElementById("ie").value;
var userPass = document.getElementById("ip").value;
window.alert(userEmail+ " "+ userPass);
firebase.auth().createUserWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
// ...
});
}
function logout(){
firebase.auth().signOut();
}
<html>
<head>
<title>Admin Login</title>
<link href="index-css.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="login-page">
<div class="form">
<p>Admin Login</p>
<form class="login-form">
<input id="ie"type="text" placeholder="Email"/>
<input id="ip"type="password" placeholder="Password"/>
<button id="loginbtn" onclick="login()">Login</button>
</form>
</div>
</div>
<script src="https://www.gstatic.com/firebasejs/5.8.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyA8QeKSDbtgq6GiSS3MBjU2i43IZgYeMRE",
authDomain: "web-app-login-a90bb.firebaseapp.com",
databaseURL: "https://web-app-login-a90bb.firebaseio.com",
projectId: "web-app-login-a90bb",
storageBucket: "web-app-login-a90bb.appspot.com",
messagingSenderId: "695872421055"
};
firebase.initializeApp(config);
</script>
<script src="index.js"></script>
</body>
</html>
Trying to create a basic login and sign up form using javascript and jQuery with firebase email/password authentication.
However I'm receiving this error "Reference.push failed: second argument must be a valid function" in my console # this line
database.ref().push(emailnew, passwordnew);
I've been looking here on stackoverflow and inside the firebase docs to see how to correct this issue but I am coming up empty handed. I also feel that my JS file might have more going on than necessary but I'm not sure how to simplify it. As of right now nothing is being pushed to the database. I'm not completely familiar with firebase so any added tips would be incredibly helpful, thanks.
Ideally with successful new user account creation or login, this splash page would then redirect the user to the actual app page.
Here is the form HTML
Sign Up
<div class="field-wrap">
<label>
Name<span class="req">*</span>
</label>
<input type="name" id="name" required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email-signup" id="emailSignup" required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Set A Password<span class="req">*</span>
</label>
<input type="password-signup" id="passwordSignup" required autocomplete="off"/>
</div>
<button type="" id="signupbutton" />Get Started</button>
</div>
<!-- User Login Form -->
<div id="login">
<h1>Welcome</h1>
<div class="field-wrap">
<label>
Email Address<span class="req"></span>
</label>
<input type="emailLogin" id="emailLogin" required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req"></span>
</label>
<input type="passwordLogin" id="passwordLogin" required autocomplete="off"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="button button-block" id="login" />Log In</button>
<div id=loginmessage>
</div>
Here is my user.js file with firebase intergration as follows:
// Initialize Firebase
var config = {
apiKey: 'AIzaSyBU1fYqhQrVskqgA0Okr3ZStPfYz0s3QWQ',
authDomain: "https://lackluster-5966e.firebaseapp.com",
databaseURL: 'https://lackluster-5966e.firebaseio.com',
projectId: "lackluster-5966e",
storageBucket: 'https://lackluster-5966e.appspot.com',
messagingSenderId: "489067404953"
};
firebase.initializeApp(config);
// var firebaseref = new Firebase("https://lackluster-5966e.firebaseapp.com");
var database = firebase.database();
var auth = firebase.auth();
var user = firebase.auth().currentUser;
console.log(config);
var emailnew;
var passwordnew;
//Collect User Data from Signup
$("#signupbutton").click(function(event){
event.preventDefault();
emailnew = $("#emailSignup").val();
passwordnew = $("#passwordSignup").val();
database.ref().push(emailnew, passwordnew); //Error occurs
console.log(emailnew);
console.log(passwordnew);
});
//Creates New User via Firebase Authentication
var promise = auth.createUserWithEmailAndPassword(emailnew, passwordnew);
promise.then(function(user) {
user.sendEmailVerification().then(function() {
// Email sent.
}, function(error) {
// An error happened.
});
//Sends User Info to firebase DB
user.updateProfile({
Name: name,
Email: emailnew
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
// Clears all of the text-boxes for user signup
$("#emailSignup").val("");
$("#passwordSignup").val("");
//User Login Event
var emailLogin = document.getElementById('emailLogin');
var passwordLogin = document.getElementById('passwordLogin');
$("#login").click(function(event){
event.preventDefault();
var email = emailLogin.value;
var password = passwordLogin.value;
var auth = firebase.auth();
var promise = auth.signInWithEmailAndPassword(email, password);
promise.catch(function (e) {
return console.log(e.message);
});
// //Page redirect
// firebase.auth().onAuthStateChanged(user => {
// if(user) {
// window.location = 'index.html';
// }
// else{
// //Do nothing.
// }
// });
// Authentication Listner
// Verifies that login credentials are correct otherwise returns error message
var Message = "<div class=\"loginmessage\">" + "Login Unsuccessful" + "</div>";
firebase.auth().onAuthStateChanged(function (firebaseUser) {
if (firebaseUser) {
console.log(firebaseUser);
} else {
$('#loginmessage').append(Message);
console.log('not logged in');
} // end else statement
}); // end function
});
// Clears all of the text-boxes for user login
$("#emailLogin").val("");
$("#passwordLogin").val("")
});
The push method expects an object as parameter.
Modify your call to this:
// the property names are up to you
database.ref().push({ email: emailnew, password: passwordnew });