Firebase Authentication not working with html form element - javascript

I'm following the Firebase examples that uses web authentication, and I'm not able to login if I use the textboxes and buttons inside a html form element.
Here is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase.js"></script>
</head>
<body>
<form id="app">
<input type="email" id="txtEmail" placeholder="Email">
<input type="password" id="txtPassword" placeholder="Password">
<button id="btnLogin">Login</button>
<button id="btnSignUp">SignUp</button>
<button id="btnLogout">Logout</button>
</form>
</body>
<script src="app.js"></script>
</html>
And the js:
(function() {
// Initialize Firebase
const config = {
apiKey: "MyData",
authDomain: "MyData",
databaseURL: "MyData",
projectId: "MyData",
storageBucket: "MyData",
messagingSenderId: "MyData"
};
firebase.initializeApp(config);
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');
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise
.catch(e => console.log(e.message));
});
btnLogout.addEventListener('click', e => {
firebase.auth().signOut();
});
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser){
console.log(firebaseUser);
btnLogout.style.display = 'block';
} else {
console.log('not logged in');
btnLogout.style.display = 'none';
}
});
}());
When I try to login, the console log rises the following message:
"It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the CDN builds, these are available in the following manner
(replace with the name of a component - i.e. auth, database, etc):
https://www.gstatic.com/firebasejs/5.0.0/firebase-.js"
If I move the inputs and buttons outside the form element, the login works perfectly.
What am I missing?

For your case best thing is to use firebase UI with CDN instead of npm and bower
No worries and no confusion, no errors (I mean less depends on our skill)
Add Firebase Authentication to your web application.
Include FirebaseUI via CDN:
Include the following script and CSS file in the tag of your page, below the initialization snippet:
<script src="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.css" />
In the Firebase console, open the Authentication section and enable email and password authentication.
ui.start('#firebaseui-auth-container', {
signInOptions: [
firebase.auth.EmailAuthProvider.PROVIDER_ID
],
// Other config options...
});
Other Providers:
ui.start('#firebaseui-auth-container', {
signInOptions: [
// List of OAuth providers supported.
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.TwitterAuthProvider.PROVIDER_ID,
firebase.auth.GithubAuthProvider.PROVIDER_ID
],
// Other config options...
});
For more info, please follow this link : https://firebase.google.com/docs/auth/web/firebaseui

Look at this index.html file, this way I can login perfectly, because I commented the form element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase.js"></script>
</head>
<body>
<!-- <form id="app"> -->
<input type="email" id="txtEmail" placeholder="Email">
<input type="password" id="txtPassword" placeholder="Password">
<button id="btnLogin">Login</button>
<button id="btnSignUp">SignUp</button>
<button id="btnLogout">Logout</button>
<!-- </form> -->
</body>
<script src="app.js"></script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase.js"></script>
</head>
<body>
<form id="app">
<input type="email" id="txtEmail" placeholder="Email">
<input type="password" id="txtPassword" placeholder="Password">
<button id="btnLogin">Login</button>
<button id="btnSignUp">SignUp</button>
<button id="btnLogout">Logout</button>
</form>
</body>
<script src="app.js"></script>
</html>
But using the html like the one I posted initially (using form element) rises the following error to the console:
"A network error (such as timeout, interrupted connection or unreachable host) has occurred."

Related

Uncaught TypeError: btnSubmit is not a function at HTMLButtonElement.onclick

I'm trying to store some user information in firebase cloud store.
The problem is I created a form to enforce the user to fill all the fields and to make the email property works well. when I put them in a form I got this error:
Uncaught TypeError: btnSubmit is not a function
at HTMLButtonElement.onclick
when I remove the form tag it works well, but the user can submit the form without filling it, which is not good.
This is my code:
//firestore code
var db = firebase.firestore();
function btnSubmit(){
var inputText = document.getElementById("fname").value;
var email = document.getElementById("email").value;
// Add a new document in collection
db.collection("users").doc().set({
name: inputText,
email: email
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
}
<html>
<head>
<title> exam.</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Cairo&display=swap" rel="stylesheet">
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="form-container">
<div class="form-container-in">
</div>
<div class="row">
<div class="left-divider"></div>
<div class="col-md-6">
<div class="form-group">
<h2 >your Information </h2>
</div>
<div class="form-group">
<form>
<label for="fname"><b> name </b></label>
<input type="text" placeholder="name " name="fname" id="fname" required>
<div class="form-group">
<label for="email"><b> email</b></label>
<input type="email" placeholder="email " name="email" id="email" required><br>
<button onclick="btnSubmit()" id="btnSubmit">go </button>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-firestore.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "---",
authDomain: "--",
databaseURL: "---",
projectId: "--",
storageBucket: "--",
messagingSenderId: "--",
appId: "--",
measurementId: "--"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="app.js"></script>
</body>
</html>
This is one of the many reasons not to use onxyz-attribute-style event handlers: Those kinds of handlers can only call global functions. Apparently, your btnSubmit isn't a global. (It would be if the code you've shown for it appeared at the top level of a non-module script, as it appears to in your question, but presumably the code in the question is an excerpt from a larger function, and not at the top-level scope of it.)
The normal error you'd get for this would be a ReferenceError because trying to read the value of an undeclared identifier causes that kind of error. The reason you're not getting that is you have id="btnSubmit" on your button element, which creates an automatic global with that name that refers to the button.
Instead, hook up your handler with modern event handling:
document.getElementById("btnSubmit").addEventListener("click", function() {
// Your handler code here
});
You can still declare the function separately if you want to, without it being a global. If you do that, hook it up from code in a scope where your btnSubmit function exists (for instance, just after it), like this:
function btnSubmit() {
// Your handler code here
}
document.getElementById("btnSubmit").addEventListener("click", btnSubmit);

Firebase database is giving an error that firebase.database.rel is not a function in web

I have been experimenting with Firebase recently. I have implemented Firebase Authentication in my apps but i am experiencing an error with Firebase realtime-database. I have searched online but there are no results for this exact problem. I have been trying to fix it but i can't, I have tried everything.
Here is my image:
Firebase Database error
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://www.gstatic.com/firebasejs/7.17.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.2/firebase-database.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "-----API KEY-------",
authDomain: "-----AUTH DOMAIN-----",
databaseURL: "----DATABASE URL----",
projectId: "----PROJECT ID----",
storageBucket: "-----STORAGE BUCKET----",
messagingSenderId: "----SENDER ID----",
appId: "-----APP ID-----",
measurementId: "----MEASURMENT ID -----"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script src="app.js"></script>
</head>
<body>
<div>
<input type="text" placeholder="Enter name" id="names">
<input type="text" placeholder="Enter name" id="rollno">
<button onclick="savedata()">Save Data</button>
</div>
</body>
</html>
I have changed firebase-app.js to firebase.js at Line 8 in the HTML above but It didn't fix my problem. Also here is my Javascript:
function savedata() {
var name = document.getElementById("names");
var roll = document.getElementById("rollno");
var student = {
name: name.value,
rollno: roll.value
}
firebase.database().rel('student').set(student)
}
Right here, i am creating an object student in my firebase realtime-database ,in which i am going to add the values of name and roll no which will all be collected from the user input.
There is no method "rel". Perhaps you meant ref().

Uncaught TypeError: Cannot read property 'uid' of null using website

I want to get registered user details from firestore into html page. When user clicks my profile page it navigate to next html page with fields like first name and last name etc.. . This fields are already entered at the time of signup page. so i want get those details from firestore into next html page. But i got the error like "Cannot read property 'uid' of null ". How to resolve that problem this is my html page :
<!doctype html>
<html lang="en">
<head>
<title> deyaPay</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-auth.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-firestore.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script>
var config = {
apiKey: "AIzaSyAJsAstiMsrB2QGJyoqiTELw0vsWFVVahw",
authDomain: "websignin-79fec.firebaseapp.com",
databaseURL: "https://websignin-79fec.firebaseio.com",
projectId: "websignin-79fec",
storageBucket: "",
messagingSenderId: "480214472501"
};
firebase.initializeApp(config);
</script>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase-firestore.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<style>
// css goes here..
</style>
<script type="text/javascript">
function myProfile() {
var user = firebase.auth().currentUser.uid;
var db = firebase.firestore();
var docRef = db.collection("deyaPayusers").doc(user);
docRef.get().then(function(doc) {
if(doc && doc.exists) {
const myData = doc.data();
const ffname = myData.FirstName;
const llname = myData.LastName;
const phonen = myData.PhoneNumber;
document.getElementById("fname").value = ffname;
document.getElementById("lname").value = llname;
document.getElementById("phone").value = phonen;
}
}).catch(function(error) {
console.log("Got an error: ",error);
});
}
</script>
</head>
<body onload='myProfile()'>
<div class= "login-form">
<form method="post">
<h2>Profile</h2>
<div class="form-group">
<input type="text" name="firstname" id="fnmae" placeholder="FirstName" class="form-control" >
</div>
<div class="form-group">
<input type="text" name="lastname" id="lnmae" placeholder="LastName" class="form-control" >
</div>
<div class="form-group">
<input type="text" name="phone" id="phone" placeholder="PhoneNumber" class="form-control" >
</div>
</form>
</div>
</body>
</html>
Your error says Cannot read property 'uid' of null. which means you are loading myProfile() this function on page load, by that time user may be null. There will be a lag to fetch auth details from firebase. Try this way
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var db = firebase.firestore();
var docRef = db.collection("deyaPayusers").doc(user.uid);
docRef.get().then(function(doc) {
if(doc && doc.exists) {
const myData = doc.data();
const ffname = myData.FirstName;
const llname = myData.LastName;
const phonen = myData.PhoneNumber;
document.getElementById("fname").value = ffname;
document.getElementById("lname").value = llname;
document.getElementById("phone").value = phonen;
}
}).catch(function(error) {
console.log("Got an error: ",error);
});
} else {
// No user is signed in.
}
});

How to send email via real server(SendGrid)

For my website, I am trying to send email to the users. I used sendgrid provider for sending the mail with nodeJS. I am new to nodeJS, I have sent the mail via the command prompt as per their instructions on their page. But I don't how to implement it on the real server. For sending emails via sendgrid I installed their package. And I want to send an email to a particular event.
function goMail()
{
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(MY_API_KEY);
const msg = {
to: '********1234#gmail.com',
from: '12345***#gmail.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
}
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div class="container">
<h2>Vertical (basic) form</h2>
<form>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" onclick="goMail();">Submit</button>
</form>
</div>
</body>
</html>
Please explain to brief how do they work on the real server.
You cannot directly include index.js file in HTML and invoke the Nodejs function. instead you should be using Express framework at Nodejs and use jQuery to post the form data. Please follow the instructions provided in the below link:
https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
Hope this answer points you to the right direction and resolve your issue.
If you have implemented your server code then just add the following route in app.js file for creating an API for sending an email to the users
app.get('/sendEmail', (req, res) => {
let sendgrid = require('sendgrid');
let SG = sendgrid('your sendgridKey');
let request = SG.emptyRequest();
request.method = 'POST';
request.path = '/v3/mail/send';
request.body = (new sendgrid.mail.Mail(
new sendgrid.mail.Email(req.body.from),
req.body.subject, // subject
new sendgrid.mail.Email(req.body.to),
new sendgrid.mail.Content('text/html', 'your html')
)).toJSON();
SG.API(request, (err, response)=> {
if (response.statusCode >= 200 && response.statusCode < 300) {
res.send(response);
});
});
or you can define this function outside of the router so that you can call this function as middleware in any route.

Firebase Anonymous Login on Form Submit Issue

I'm trying to make it so that when I user clicks the submit button on my sign in form, they will be signed in as an anonymous user in Firebase. I know my submit button is triggering the jQuery submit event because the alert in it is being displayed. However, even though the submit button triggers the jQuery submit event, the signInAnonymously method is not being called for some reason. I've also tried using a putting the signInAnonymously call in a separate function and using the form onsubmit attribute but that did not work either. Here is my code (I've omitted my config details for security purposes):
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Escape Room</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="resources/bootstrap/css/bootstrap.min.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="styles.css">
<!-- jQuery -->
<script src="resources/jquery/jquery-3.1.1.slim.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
//Initialize authentication
var auth = firebase.auth();
// Handle authenticated users
auth.onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var uid = user.uid;
// ...
} else {
// User is signed out.
// ...
}
// ...
});
// When the DOM has loaded
$(document).ready(function(e) {
$('#signIn').submit(function(e) {
// Prevent the page from refreshing
e.preventDefault();
alert("test");
// Authenticate user
auth.signInAnonymously().catch(function(error) {
alert('test2');
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.error(error);
});
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<form id="signIn">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" placeholder="Your Name">
</div>
<div class="form-group">
<label for="vest">Vest Number</label>
<input type="text" class="form-control" placeholder="Vest Number">
</div>
<button type="submit" class="btn btn-primary">Start</button>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="resources/jquery/jquery-3.1.1.slim.min.js"></script>
<script src="resources/tether/js/tether.min.js"></script>
<script src="resources/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
I'm relatively new to Firebase and this has got me baffled, so any help would be greatly appreciated!
I found out what was going wrong. Since I never called firebase.auth().signOut() it was keeping me logged in as the same user so it did not create a new user each time I submitted the form because I was already logged in as a user. I added window.onload = auth.signOut(); to the script in my head and now a new user is created each time I press the submit button.

Categories

Resources