Unable to add data into firebase realtime database using javascript - javascript

var config = {
apiKey: "A**********************kBs",
authDomain: "the**********.firebaseapp.com",
databaseURL: "https://***********.firebaseio.com",
projectId: "the-o***********nette",
storageBucket: "the***********.appspot.com",
messagingSenderId: "6***********6"
};
firebase.initializeApp(config);
$("#register").click(
function() {
var email=$("#regEmail").val();
var password=$("#regPass").val();
var fname=$("#regfName").val();
var lname=$("#reglName").val();
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage)
});
alert( "you have successfully registered");
// Get a reference to the database service
var database = firebase.database();
var userId = firebase.auth().currentUser;
firebase.database().ref('users/' + userId).set({
fname: fname,
lname: lname,
email: email,
})
.catch(function(error) {
var errormsg=error.message;
console.log(errormsg);
});
}
);
The createuserwithemailandpassword is working properly. But I am not able to add anything into the database. No error log is reported. The var is mentioned in the HTML file. Let me know if anything else is needed. thanks!

You are passing the full user object instead of the uid. Please try this:
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('users/' + userId).set();

Related

Uncaught Reference Error : firebase not defined at main.js

Am trying to Connect Firebase to a Contact Form,
where requires the user to type and submit Fullname , Email and also Message.
But I face Uncaught ReferenceError: firebase is not defined at my main.js file
form my console.
I tried different solution but I couldn't be able to solve it.
Here is my script tag in my index.html
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
</script>
<script src="main.js"></script>
here is my Main.js code
var config = {
apiKey: "xxxxx",
authDomain: "xxxxx",
databaseURL: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx"
};
firebase.initializeApp(config);
var emailRef = firebase.database().ref('emails');
// Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);
// Submit form
function submitForm(e){
e.preventDefault();
//Get values
var FullName = getInputval('FullName');
var Email =getInputval('Email');
// save message
saveMessage(FullName,Email);
// Show alert
document.querySelector('.alert').style.display = 'block';
// Hide alert after 3 seconds
setTimeout(function(){
document.querySelector('.alert').style.display = 'none';
},3000);
// Clear form
document.getElementById('contactForm').reset();
}
// Function to get form values
function getInputval(id){
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(Fullname, Email,){
var newEmailRef = emailRef.push();
newEmailRef.set({
Fullname: Fullname,
Email:Email
});
}
Since you're initializing firebase here, it should be something like this:
const firebase = initializeApp(config);
For more info you can have a look here.

How can I get the user profile and name from Firebase?

My code shows only undefined. I want it to show user name, profile image, and user email. Thanks for help in advance.
var firebaseConfig = {
//My Configuration
};
firebase.initializeApp(firebaseConfig);
var mainUser = firebase.auth().currentUser;
var userNameId, userEmailId, photoUrl, uid, emailVerified;
if (mainUser != null) {
userNameId = user.displayName;
userEmailId = user.email;
photoUrl = user.photoURL;
emailVerified = user.emailVerified;
uid = user.uid; // The user's ID, unique to the Firebase project. Do NOT use
// this value to authenticate with your backend server, if
// you have one. Use User.getToken() instead.
}
document.write(userNameId);
document.write(userEmailId);
document.write(photoUrl);
document.write(emailVerified);
document.write(uid);
Your user variable is not defined. Change the mainUser to user instead:
var firebaseConfig = {
apiKey: "AIzaSyCfX0ye2p4W8Jq2Za3H0_nRpgtFAlGxFxA",
authDomain: "trendy-cart-79671.firebaseapp.com",
databaseURL: "https://trendy-cart-79671.firebaseio.com",
projectId: "trendy-cart-79671",
storageBucket: "trendy-cart-79671.appspot.com",
messagingSenderId: "563099031291",
appId: "1:563099031291:web:1fe8d3c43e2dfd8429425e"
};
firebase.initializeApp(firebaseConfig);
var user = firebase.auth().currentUser;
var userNameId, userEmailId, photoUrl, uid, emailVerified;
if (user != null) {
userNameId = user.displayName;
userEmailId = user.email;
photoUrl = user.photoURL;
emailVerified = user.emailVerified;
uid = user.uid; // The user's ID, unique to the Firebase project. Do NOT use
// this value to authenticate with your backend server, if
// you have one. Use User.getToken() instead.
}
document.write(userNameId);
document.write(userEmailId);
document.write(photoUrl);
document.write(emailVerified);
document.write(uid);

How do I redirect after auth users register to collection in Firestore?

I'm trying to connect a user to the user collection in firestore. And after then,I'm trying to redirect login page.But not work.
I have implemented this page for reference
How do I link auth users to collection in Firestore?
var express = require('express');
const firebase = require('firebase/app');
require("firebase/auth");
require("firebase/database");
require("firebase/firestore");
var router = express.Router();
var moment = require('moment');
var firebaseConfig = {
apiKey: "hogehoge",
authDomain: "hogehoge.firebaseapp.com",
databaseURL: "https://hogehoge.firebaseio.com",
projectId: "hogehoge",
storageBucket: "hogehoge.appspot.com",
messagingSenderId: "hogehoge",
appId: "hogehoge"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore();
let auth = firebase.auth();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('register', { title: 'register page' });
});
router.post('/', function(req, res, next) {
var userName = req.body.user_name;
var email = req.body.email;
var password = req.body.password;
var createdAt = moment().format('YYYY-MM-DD HH:mm:ss');
var promise = auth.createUserWithEmailAndPassword(email, password);
// If there is any error stop the process.
promise.catch(function (error) {
var errorCode = error.code;
console.log(`GOT ERROR: ` + errorCode)
});
// When no errors create the account
promise.then(function () {
var userUid = auth.currentUser.uid;
db.collection('users').doc(userUid).set({
email: email,
name: userName,
password: password,
created_at: createdAt
});
res.redirect('/login');
});
});
module.exports = router;
If I don't write a redirect,
//res.redirect('/login');
registration is successful, but page is timeout.
So I'm writing a redirect process(not comment out), but this time the registration process is not done.
How can I redirect after registration is complete?
I'm not really sure but I would say that you have to fulfill your promise of your db.collection('users').doc(userUid).set(...). So try this:
promise.then(function () {
var userUid = auth.currentUser.uid;
db.collection('users').doc(userUid).set({
email: email,
name: userName,
password: password,
created_at: createdAt
}).then(function () {
res.redirect('/login');
});
});

I keep getting the error firebase.database is not a function

I'm trying to link my contact form in a portfolio website to firebase and keep getting (firebase.database is not a function) in my console
This is for the web, using pure javascript
var firebaseConfig = {
apiKey: "AIzaSyCzX3r8CFw84WSBuCSXR1fWM_hDrwtGMSs",
authDomain: "portfolio-4c243.firebaseapp.com",
databaseURL: "https://portfolio-4c243.firebaseio.com",
projectId: "portfolio-4c243",
storageBucket: "",
messagingSenderId: "745737502175",
appId: "1:745737502175:web:a26e5b0baa3769c9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var messagesRef = firebase.database().ref('messages');
document.getElementById('contactForm').addEventListener('submit', submitForm);
function submitForm(e) {
e.preventDefault();
var name = getInputVal('name');
var email = getInputVal('email');
var message = getInputVal('message');
saveMessage(name, email, message);
}
// Function get value
function getInputVal(id) {
return document.getElementById(id).value;
}
//Save
function saveMessage(name, email, message) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
email: email,
message: message
})
}
This error is very common and arises because either you have not configured your config object correctly or the script tag required for using that particular functionality is missing.
In your case the config object looks fine so you have to add this script in your page
<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-database.js"></script>
But please note that this script is to be added only after the core script for firebase app
<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-app.js"></script>
and for future if you want to use any other service from Firebase like Firestore or so, just make sure you have that particular script tag in there (with the config object correctly setted up).

create users on firebase using its authenticate methods

i tried sending the credentials and this error appears.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=*******. (Reason: CORS request did not succeed).
(function () {
var config = {
apiKey: "*******",
authDomain: "*******",
databaseURL: "*******",
projectId: "*******",
storageBucket: "*******",
messagingSenderId: "*******"
};
firebase.initializeApp(config);
const email = document.getElementById('email');
const password = document.getElementById('password');
const btnSignUp = document.getElementById('btnSignUp');
btnSignUp.addEventListener('click', e => {
const mail = email.value;
const pass = password.value;
firebase.auth().createUserWithEmailAndPassword(mail, pass).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
});
}());
How do I solve the CORS request blocked?
Your firebase imports are wrong, use this:
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.1.0/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.1.0/firebase-auth.js"></script>

Categories

Resources