i'm trying to use firebase in angular but don't know why my localhost cannot function with my javascript.
It functions well if i put all the code in index.html but i just wondered why it cannot function in my contact.component.html when i using localhost.
looks like my javascript cannot function in html
enter image description here
//here is my main.js
// Initialize Firebase (ADD YOUR OWN DATA)
var config = {
apiKey: "...",
authDomain: "listing-ed9ac.firebaseapp.com",
databaseURL: "https://listing-ed9ac.firebaseio.com",
projectId: "listing-ed9ac",
storageBucket: "listing-ed9ac.appspot.com",
messagingSenderId: "122342013620"
};
firebase.initializeApp(config);
// Reference messages collection
var messagesRef = firebase.database().ref('messages');
// Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
e.preventDefault();
// Get values
var name = getInputVal('name');
var company = getInputVal('company');
var email = getInputVal('email');
var phone = getInputVal('phone');
var message = getInputVal('message');
// Save message
saveMessage(name, company, email, phone, message);
// Clear form
document.getElementById('contactForm').reset();
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(name, company, email, phone, message) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
company: company,
email: email,
phone: phone,
message: message
});
}
//here is my contact.component.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>try</title>
</head>
<body>
<section id="showcase">
<div class="container">
<h1>
Contact Us
</h1>
</div>
</section>
<html>
<body>
<div class="container">
<h1 class="brand"><span>Car</span> Rental</h1>
<div class="wrapper animated bounceInLeft">
<div class="company-info">
<h3>Car Rental</h3>
<p>
Get in touch with us via the Contact Form. Car Rental will be in touch with you shortly.
</p>
</div>
<div class="contact">
<h3>Email Us</h3>
<div class="alert">Your message has been sent</div>
<form id="contactForm">
<p>
<label>Name</label>
<input type="text" name="name" id="name" required>
</p>
<p>
<label>Company</label>
<input type="text" name="company" id="company">
</p>
<p>
<label>Email Address</label>
<input type="email" name="email" id="email" required>
</p>
<p>
<label>Phone Number</label>
<input type="text" name="phone" id="phone">
</p>
<p class="full">
<label>Message</label>
<textarea name="message" rows="5" id="message"></textarea>
</p>
<p class="full">
<button type="submit">Submit</button>
</p>
</form>
</div>
</div>
</div>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script src="main.js"></script>
</body>
</html>
<section id="showcase2">
<div class="container">
<p>
HAWK RENT A CAR (M) SDN BHD
</p>
<p>
No 4 Jalan SS13/3E,Subang Jaya Industrial Estate, 47500 Subang Jaya,Selangor Darul Ehsan
</p>
<p>
Tel: 1300886488(Within Malaysia) / +603-56316488
</p>
<p>
Fax : +603-56356466
</p>
<p>
Email: reservations#hawkrentacar.com.my
</p>
</div>
</section>
</body>
</html>
<footer>
<p>Copyright © 2017 Designed by ckyong </p>
</footer>
It old question but lot of newbies to Angular (2+) might face this.
The code snippets shared only work with pure JavaScript (vanilla JavaScript).
For Angular the different way, install angularfire2 module, and proceed. The syntax is different in the angularfire2 module.
If I am right the TypeScript using angularfire2 will be converted to equivalent JavaScript (similar to your code you shared)
Related
<form class="modal-content" id="bookingForm">
<div class="formContainer">
<h1>Booking Form</h1>
<p>Please fill in this form to Book The Trip.</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required id="email">
<label><b>Package</b></label>
<input type="text" id="packageFields" name="teste2">
<label for="psw"><b>Name</b></label>
<input type="text" placeholder="Enter Name" name="name" required id="name">
<label for="psw-repeat"><b>Phone No.</b></label>
<input type="tel" placeholder="Enter Phone No." name="psw-repeat" required id="phone">
<label for="psw-repeat"><b>Date Of Journey</b></label>
<input type="date" placeholder="Enter Phone No." name="psw-repeat" required id="date">
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="signupbtn">Confirm Booking</button>
<button type="button" onclick="document.getElementById('bookingForm').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</div>
</form>
</script>
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
<!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="/__/firebase/7.14.5/firebase-app.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="/__/firebase/7.14.5/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="/__/firebase/7.14.5/firebase-auth.js"></script>
<script src="/__/firebase/7.14.5/firebase-firestore.js"></script>
<script src="/__/firebase/init.js"></script>
<script src="bookingSubmit.js"> </script>
This Is The Html And The JavaSript Is Given Below:
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "hxxxxxxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxxx.firebaseio.com",
projectId: "xxxxxxxxx",
storageBucket: "xxxxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxxx",
appId: "x:xxxxxxxxxxxx:web:xxxxxxxxxxxxxxxxxxxxxx",
measurementId: "G-xxxxxxxxxx"
};
//reference messages collection
var firestore = firebase.firestore();
const submitBtn = document.querySelector(".signupbtn");
let email = document.querySelector('#email');
let packageFields = document.querySelector('#packageFields');
let name = document.querySelector('#name');
let phone = document.querySelector('#phone');
let date = document.querySelector('#date');
const db = firestore.collection("BookingData");
submitBtn.addEventListner('click', function(){
let userEmailInput = email.value;
let userPackageInput = packageFields.value;
let userNameInput = name.value;
let userPhoneInput = phone.value;
let userDateInput = date.value;
db.doc()
.set({
email:userEmailInput,
package:userPackageInput,
name:userNameInput,
phone:userPhoneInput,
date:userDateInput
})
.then(function(){
console.log("Data Saved");
})
.catch(function(error){
console.log(error);
});
});
I am trying to Store The Data Of My Contact Form in firebase. But Its Giving The Error
Uncaught TypeError: submitBtnis null
at bookingSubmit.js:27
I Am putting the script at the end then why is it giving this error?
What is its cause and how to solve it...??
You should add an id on your element rather than a class.
<button type="submit" id="signupbtn" class="signupbtn">Confirm Booking</button>
const submitBtn = document.querySelector("#signupbtn");
Also there is a typo in the addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
It should be
submitBtn.addEventListener('click', function(e){
//Remove default form submit behaviour.
e.preventDefault();
//...
and not
submitBtn.addEventListner('click', function(){ //Typo in addEventListner
You are using:
const submitBtn = document.querySelector("#signupbtn");
to select
<button type="submit" class="signupbtn">Confirm Booking</button>
You either need to select based on class name: ".signupbtn" or set an ID and not a class on the element.
My renderer.js code:
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "some API key",
authDomain: "some auth domain",
databaseURL: "some database url",
projectId: "some project id",
storageBucket: "some storagebucket",
messagingSenderId: "some messaging sender id",
appId: "some app id",
measurementId: "some measurement id"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var bcont = document.getElementById('bcont');
bcont.addEventListener('click',function(){
var firstname = document.getElementById('fn').value;
var lastname = document.getElementById('ln').value;
var email = document.getElementById('email').value;
var password = document.getElementById('pass1').value;
var cpassword = document.getElementById('pass2').value;
firebase.auth().createUserWithEmailAndPassword(email,password).catch(function(error){
if(error != null){
console.log(error.message);
return;
}
alert('Success');
})
});
index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<link rel="stylesheet" href="../assets/css/main.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<div class="bbg">
<div class="full">
<div class="left">
<div>
<t id="welcome">Welcome to</t>
<div>
<t id="title">This Thing</t>
<br>
<br>
<t id="signuptitle">Signup</t>
<img id="fimg" src="../assets/images/fpimg.png">
</div>
</div>
</div>
<div class="right">
<div class="wbg">
<div>
<br/>
<t class="formtext">First Name</t>
</div>
<input id="fn" class="input">
<br/>
<div>
<t class="formtext">Last Name</t>
</div>
<input id="ln" class="input">
<br/>
<div>
<br/>
<t class="formtext">Email Address</t>
</div>
<input id="email" class="input">
<br/>
<div>
<br/>
<t class="formtext">Password</t>
</div>
<input id="pass1" class="input" type="Password">
<br/>
<div>
<t class="formtext">Confirm Password</t>
</div>
<input id="pass2" class="input" type="Password">
<br/>
<br/>
<button id="bcont" class="b_cont"><b>Continue</b></button>
<br/>
<br/>
<br/>
<t class="textfooter">Already have an account? <t class="a-login"> Login</t></t>
</div>
<!--<script>
function continueCheck(){
if(document.getElementById('pass1').textContent != document.getElementById('pass2').textContent){
document.getElementById('pass1').style.borderColor = '#e60200';
document.getElementById('pass2').style.borderColor = '#e60200';
}
}
</script>-->
</div>
</div>
</div>
<!-- You can also require other files to run in this process -->
<script src="renderer.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
</body>
</html>
I get the error in the console of Uncaught Reference Error: firebase is not defined.
How would I be to fix this?
Also:
How can I store first and last name as well as email + password?
Please note: this is the correct link and I have only the Email/Password sign-in method enabled.
Not sure what to do here, any help would be appreciated!
You should put your includes in the right order:
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
<script src="renderer.js"></script>
So renderer.js knows firebase exists.
I'm trying to set up a login/signup website (Using Firebase Auth), and I am getting a "too many redirects" error when I try to sign up on my site. How can I fix this?
Running HTML5 with Firebase Auth
<form action="index.html" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<br>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<br>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
<img src="BF116-11KM.jpg" alt="Avatar" class="avatar">
</div>
</form>
<p id="log"></p>
</center>
</div>
<script>
function logSubmit(event)
{
var database = firebase.database();
function testResults(form)
{
var email = form.email.value;
var password = form.psw.value;
}
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error)
{
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
log.textContent = 'Sorry, Something went wrong. Please try again in a moment';
// ...
});
log.textContent = 'Signup Complete! Please login on the main page';
event.preventDefault();
}
const form = document.getElementById('form');
const log = document.getElementById('log');
form.addEventListener('submit', logSubmit);
</script>
Expected results would be the account appearing in my firebase console, but actual results include the "too many redirects" error.
Two notices:
your second input-element (password) never closes
how is the index.html supposed to support your form-submit?
I am using firebase to signup users using email and password on my website. I have enabled email and password signup on my console. When I signup an user on the web page, the user email and password do not get passed to Firebase, and no error is displayed neither.
Her is my front end code
<!DOCTYPE html>
<html>
<head>
<title>Registration </title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-database.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="signup.js" defer></script>
</head>
<body>
<form id="form">
<div class="header">
<h2>Sign up as a Language Learner</h2>
</div>
<div class="input">
<input id="username" type="text" name="username" placeholder="Username">
</div>
<div class="input">
<input id="email" type="email" name="email" placeholder="Email">
</div>
<div class="input">
<input id="password1" type="password" name="password_1" placeholder="Password">
</div>
<div class="input">
<input id="password2" type="password" name="password_2" placeholder="Confirm Password">
</div>
<div>
<p id="message">
</p>
</div>
<div class="input">
<button id="register_button" class="btn" name="signup">Register</button>
<p class="input">Already a member? Sign in
  Cancel
</p>
</div>
</form>
<div id="signup_success">
<h2>Sign-up Successful!</h2>
</div>
</body>
</html>
Here is my signup.js file:
var password2 = document.querySelector("#password2").value;
var register_button = document.querySelector("#register_button");
var config = {
apiKey: "111",
authDomain: "222",
databaseURL: "333",
projectId: "444",
storageBucket: "555",
messagingSenderId: "666"
};
firebase.initializeApp(config);
register_button.onclick = function() {
var email = document.querySelector("#email").value;
var password1 = document.querySelector("#password1").value;
firebase.auth().createUserWithEmailAndPassword(email, password1).catch(function(error) {
alert("hello");
var errorCode = error.code;
var errorMessage = error.message;
document.querySelector("#message").innerHTML = errorCode + ": " + errorMessage;
})
}
I have my config setup properly with the data from the console. If I get rid of register_button.onclick = function(), the firebase.auth().createUserWithEmailAndPassword executes. I tried to add register_button.addEventListener("click", register_user, false); at the end and it does not work either.
I have no idea what is wrong with this, any help and advice is very appreciated. Thanks in advance.
*Edit: Thanks to #Fire-in-D-Hole below, it was due to my tag in HTML, using tag messes up with what we submit on Firebase. Lesson learned: never use when using Firebase
Your code is absolutely Correct. However, There seems to be an Extra Space in the method createUserWithEmailAndPassword(email, password1) which is causing the issue.
Please change it to createUserWithEmailAndPassword(email,password1).
Also, When I click on Register it seems you are using Form Tagand the values are being displayed in the Address bar(See Below). Suggest you to Please check as you might not want to show Details in the Address bar.
Users Registered Screenshot:
Lastly, you are using Two fields as password make sure you have the logic Written that both the password fields have to be matched. Adding the Code below which I tried and it doesn't have Form tags.
var password2 = document.querySelector("#password2").value;
var register_button = document.querySelector("#register_button");
var config = {
apiKey: "111",
authDomain: "1111",
databaseURL: "1111",
projectId: "1111",
storageBucket: "11111",
messagingSenderId: "111"
};
firebase.initializeApp(config);
register_button.onclick = function() {
var email = document.querySelector("#email").value;
var password1 = document.querySelector("#password1").value;
var password2= document.querySelector("#password2").value;
//alert("heyman im in register button");
//console.log("Email" +email);
// console.log("password1 Value" +password1);
// console.log("password2 Value" +password2);
firebase.auth().createUserWithEmailAndPassword(email, password1).catch(function(error) {
//alert("hello");
var errorCode = error.code;
var errorMessage = error.message;
document.querySelector("#message").innerHTML = errorCode + ": " + errorMessage;
});
}
<!DOCTYPE html>
<html>
<head>
<title>Registration </title>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase-database.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script src="signup.js" defer></script>
</head>
<body>
<div class="header">
<h2>Sign up as a Language Learner</h2>
</div>
<div class="input">
<input id="username" type="text" name="username" placeholder="Username">
</div>
<div class="input">
<input id="email" type="email" name="email" placeholder="Email">
</div>
<div class="input">
<input id="password1" type="password" name="password_1" placeholder="Password">
</div>
<div class="input">
<input id="password2" type="password" name="password_2" placeholder="Confirm Password">
</div>
<div>
<p id="message">
</p>
</div>
<div class="input">
<button id="register_button" class="btn" name="signup">Register</button>
<p class="input">Already a member? Sign in
  Cancel
</p>
</div>
<div id="signup_success">
<h2>Sign-up Successful!</h2>
</div>
</body>
</html>
You need to use the .onAuthStateChanged observer to handle the signin state change.
I've been trying to setup a simple form that will send an email to the user upon submission. I've been working with nodejs and have installed nodemailer to help aid me. I'm using gmail as the SMTP server, and was encountering some issues. Here is the html:
<title> Schedule an Appointment - Name </title>
<link rel="stylesheet" type="text/css" href="public/styles.css">
<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="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="public/script.js"></script>
<ul id="nav">
<li> Home <br>
<br>
<li><a class="active" href=""> Appointment </a> <br>
<br>
<li> Build <br>
<br>
<li> Contact <br>
<br>
</ul>
<div id="schedulePage">
<h4> Schedule an Appointment </h4>
<div id="fullForm">
First Name: <input id="firstname" type="text" name="firstname" placeholder="First Name..."> <br>
<br>
Last Name: <input id="lastname" type="text" name="lastname" placeholder="Last Name..."> <br>
<br>
Email: <input id="email" type="text" name="email" placeholder="Email..."> <br>
<br>
Phone Number: <input id="phone" type="text" name="phone" placeholder="Callback Number..."> <br>
<br>
<input id="send_email" type="submit" name="submit" value="Submit">
<span id="message"></span>
</div>
</div>
And the scripts:
$(document).ready(function(){
var from,to,subject,text;
$("#send_email").click(function(){
to=$("#email").val();
firstname=$("#firstname").val();
lastname=$("#lastname").val();
$("#message").text("Sending E-mail...Please wait");
$.get("http://localhost:4000/send",{to:to,subject:firstname,text:lastname},function(data){
if(data=="sent"){
$("#message").empty().html(" Email is been sent at " + to + " . Please check inbox !");
}
});
});
First, you need to enable less secure application in Gmail
How to enable less secure apps in google
then install node-mailer
npm i nodemailer
paste this function in your code
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport('smtps://yourmail%40gmail.com:yourpass#smtp.gmail.com');
// setup e-mail data with unicode symbols
function sendmail(to,subject,text,html,info) {
var mailOptions = {
from: '"Testing Mail" <youmail#gmail.com>', // sender address
to: to, // list of receivers
subject: subject, // Subject line
text: text, // plaintext body
html: html // html body
};
transporter.sendMail(mailOptions, function(error, infoo){
var res={
responsecode:''
}
if(error){
res.responsecode=401;
return info(new Error(res.responsecode),null);
}
res.responsecode=200;
info(null,res.responsecode+infoo.response);
});}
now call the function
app.get('/send',function (req,res) {
//pass value from your html form here
sendmail('to', 'subject', 'body', '<h1>its Html</h1>', function (err, info) {
if (err) {
console.log("Error is " + err)
return
}
console.log("Email sent. " + info)
})})