Can Not Store Data From Contact Form To Firebase - javascript

I am trying to send the data of my user to firebase using the code given below:
var firestore = firebase.firestore();
var messagesRef = firestore.collection("BookingData");
//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
//get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');
}
// function to get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
//save messages
function saveMessage(email, packageFields, name, phone, date) {
messageRef.add({
email:email,
packageFields:packageFields,
name:name,
phone:phone,
date:date
}).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
But nothing is happening.
I am not able to send the data to firebase databse.
it also shows a warning called:
[2020-05-30T03:38:27.083Z] #firebase/app:
Warning: Firebase is already defined in the global scope. Please make sure
Firebase library is only loaded once.
How can I Solve this problem? Please Help/\
Thanks in advance.

Ok, I got The Error I was Not calling The Function. The correct code is:
var firestore = firebase.firestore();
var messagesRef = firestore.collection("BookingData");
//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
//get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');
saveMessage(email, packageFields, name, phone, date);
}
// function to get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
//save messages
function saveMessage(email, packageFields, name, phone, date) {
messageRef.add({
email:email,
packageFields:packageFields,
name:name,
phone:phone,
date:date
}).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}

Related

How to fix random number generate in the child db column in firebase?

So I want to submit this web form to firebase using js script and live server that in visual studio code.
But after the submit, there is a child column with random numbers like this. I want to give a value of the name column "lakshan" to that column. How I do that ?
Current result is messages is Object
I want messages as Array
This is the js code
// Initialize Firebase (ADD YOUR OWN DATA)
var firebaseConfig = {
apiKey: "api key here",
authDomain: "test-a137f.firebaseapp.com",
databaseURL: "https://test-a137f.firebaseio.com",
projectId: "test-a137f",
storageBucket: "test-a137f.appspot.com",
messagingSenderId: "id here",
appId: "appId goes here",
measurementId: "the measurementId"
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
// Reference messages collection
var messagesRef = firebase.database().ref('Admins');
// 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);
// 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 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
});
}
The random number you get is a unique key generated by the push() method.
If you want to use your own key you need to use the set() method as follows:
var messagesRef = firebase.database().ref('Admins');
var childNode = 'lakshan';
// Or var childNode = 'Alex';
// Or var childNode = 'Denis';
messagesRef.child(childNode).set({
name: name,
company:company,
email:email,
phone:phone,
message:message
});
This is how I wanted. Thank you Renaud ;)
var childNode = name;
// Or var childNode = 'Alex';
// Or var childNode = 'Denis';
messagesRef.child(childNode).set({
name: name,
company:company,
email:email,
phone:phone,
message:message
});

Duplication check of Email id and Phone number in Firebase database using JavaScript

I'm completely new to firebase. I'm creating a basic contact form for my application and connected that to the firebase database. I don't have any authentication for my application. . I have set all the rules to True . I want to prevent duplication, if there exists phone number and email in database I want to display an error message.
Below is my code which I have tried
firebase.initializeApp(firebaseConfig);
// Reference messages collection
// Listen for form submit
document.getElementById('contactform1').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
e.preventDefault();
// Get values
var fname = getInputVal('fname');
var lname = getInputVal('lname');
var email = getInputVal('email');
var phone = getInputVal('phone');
var skills = getInputVal('skills');
var jobId = getInputVal('jid');
var linkedin = getInputVal('linkedin');
var github = getInputVal('github');
var location = getInputVal('location');
// Save message
saveMessage(fname, lname, email, skills, phone, jobId, linkedin, github, location, );
// file upload
var fileButton = document.getElementById("fileButton");
var file = fileButton.files[0];
firebase.storage().ref('self/' + file.name).put(file);
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(fname, lname, email, skills, phone, jobId, linkedin, github, location) {
firebase.database().ref().child('self/data/' + phone).set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
//snapshot to check the values in database
firebase.database().ref().child('self/data/' ).on('child_added', snap => {
var name = snap.child('name').val();
var email = snap.child('email').val();
var phone = snap.child('phone').val();
var skills = snap.child('skills').val();
var jobId = snap.child('jobId').val();
var linkedin = snap.child('linkedin').val();
var github = snap.child('github').val();
var location = snap.child('location').val();
$('#table_bdy').append('<tr><td>' + name + '</td><td>' + email + '</td><td>' + phone + '</td><td>' + skills + '</td><td>' + jobId + '</td><td>' + location + '</td><td>' + github + '</td><td>' + linkedin + '</td></tr>')
})
Before saving the new values to the database, retrieve the data from the database and check if the email written in the form is the same as an email retrieved from the database. For example:
var newEmail = getInputVal('email');
firebase.database().ref().child('self/data/' ).on('child_added', snap => {
var name = snap.child('name').val();
var email = snap.child('email').val();
if(newEmail.trim() === email.trim())
{
console.log("email already exists in the database");
}
else
{
saveMessage(fname, lname, newEmail, skills, phone, jobId, linkedin, github, location);
}
});
Try the following:
firebase.initializeApp(firebaseConfig);
// Reference messages collection
// Listen for form submit
document.getElementById('contactform1').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
e.preventDefault();
// Get values
var fname = getInputVal('fname');
var lname = getInputVal('lname');
var newEmail = getInputVal('email');
var newPhone = getInputVal('phone');
var newskills = getInputVal('skills');
var newjobId = getInputVal('jid');
var newlinkedin = getInputVal('linkedin');
var newgithub = getInputVal('github');
var newlocation = getInputVal('location');
saveMessage(fname, lname, newEmail, newskills, newPhone, newjobId, newlinkedin, newgithub, newlocation);
}
function saveMessage(fname, lname, newEmail, skills, phone, jobId, linkedin, github, location) {
let ref = firebase.database().ref().child('self/data/');
ref.on('value', snap => {
if(snap.exists())
{
snap.forEach(childSnapshot => {
var name = childSnapshot.child('name').val();
var email = childSnapshot.child('email').val();
var phone = childSnapshot.child('phone').val();
var skills = childSnapshot.child('skills').val();
var jobId = childSnapshot.child('jobId').val();
var linkedin = childSnapshot.child('linkedin').val();
var github = childSnapshot.child('github').val();
var location = childSnapshot.child('location').val();
var status = childSnapshot.child('status').val();
console.log(status);
if (newEmail.trim() === email.trim())
{ //check if email exists
console.log("email already exists in the database");
}
else
{
console.log('hello');
firebase.database().ref().child('self/data/' + phone).set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
});
}
else
{
firebase.database().ref().child('self/data/' + phone).set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
});
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
First you need to retrieve the values from the form, and then call the method saveMessage in the method check if node self/data exists, then retrieve the data and check if email already exists in the database.

Uncaught Error: Reference.push failed:

So I am using cryptojs and firebase to send an encrypted message and then display that encrypted message in the chat box. I am able to send a regular message without any encryption just fine but when I encrypt the message. I end up getting this error:
Uncaught Error: Reference.push failed: first argument contains a function in property 'messages.text.init' with contents = function () {
subtype.$super.init.apply(this, arguments);
I think because I am pushing an encryption of the message it is a function.
Not sure though.
messageForm.addEventListener("submit", function (e) {
e.preventDefault();
var user = auth.currentUser;
var userId = user.uid;
if (user.emailVerified) {
// Get the ref for your messages list
var messages = database.ref('messages');
// Get the message the user entered
var message = messageInput.value;
var myPassword = "11111";
var myString = CryptoJS.AES.encrypt(message, myPassword);
// Decrypt the after, user enters the key
var decrypt = document.getElementById('decrypt')
// Event listener takes input
// Allows user to plug in the key
// function will decrypt the message
decrypt.addEventListener('click', function (e) {
e.preventDefault();
// Allows user to input there encryption password
var pass = document.getElementById('password').value;
if (pass === myPassword) {
var decrypted = CryptoJS.AES.decrypt(myString, myPassword);
document.getElementById("demo0").innerHTML = myString;
// document.getElementById("demo1").innerHTML = encrypted;
document.getElementById("demo2").innerHTML = decrypted;
document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
}
});
// Create a new message and add it to the list.
messages.push({
displayName: user.displayName,
userId: userId,
pic: userPic,
text: myString,
timestamp: new Date().getTime() // unix timestamp in milliseconds
})
.then(function () {
messageStuff.value = "";
})
.catch(function (error) {
windows.alert("Your message was not sent!");
messageStuff;
});
Look at this line of code:
var myString = CryptoJS.AES.encrypt(message, myPassword);
myString isn't a string. I believe it's a CipherParams object. (Reading from the documentation here.) You're then trying to make that object a field in the database:
messages.push({
displayName: user.displayName,
userId: userId,
pic: userPic,
text: myString,
timestamp: new Date().getTime() // unix timestamp in milliseconds
})
This isn't going to work. You need to store a string instead of an object there. Try calling toString() the return value of encrypt() to store a string that you can later convert back to whatever you need:
messages.push({
displayName: user.displayName,
userId: userId,
pic: userPic,
text: myString.toString(),
timestamp: new Date().getTime() // unix timestamp in milliseconds
})

Parse.Cloud.run not recognizing variables

I am trying to link my website to a Parse server using mongodb. It was running well, and saving so i could see in parse dashboard, and mlab. I attempted to add a new variable which resulted in me messing something up. When this get run it throws an error saying address is not defined on the line with Parse.Cloud.run.
document.getElementById("btn").addEventListener("click", function(){
var name = document.getElementById('inp1').value;
var address = document.getElementById('inp2').value;
var city = document.getElementById('inp3').value;
var state = document.getElementById('inp4').value;
var zipcode = document.getElementById('inp5').value;
var Apartment = Parse.Object.extend("Apartment");
var apartment = new Apartment();
apartment.set("name", name);
apartment.set("address", address);
apartment.set("city", city);
apartment.set("state",state);
apartment.set("zipcode", zipcode);
apartment.save(null, {
success: function(apartment) {
// Execute any logic that should take place after the
object is saved.
alert('New object created with objectId: ' + prod.id);
},
error: function(error) {
// Execute any logic that should take place if the save
fails.
// error is a Parse.Error with an error code and
description.
alert('Failed to create new object, with error code: ' +
error.description);
}
});
});
Parse.Cloud.run("registerApartment",{"name":name,"address":address,"city":
city, "state": state,"zipcode":zipcode,"map":map}, {
success: function(savedApartment){
console.log(savedApartment);
}, error: function(error){
console.log(error);
}
})
thank you ahead of time!
cloud code
Parse.initialize('#');
Parse.serverURL = 'http://localhost:1337/parse';
Parse.Cloud.define("registerApartment", function(req,res){
var params = request.params;
var name = params.name;
var address = params.address;
var city = params.city;
var state = params.state;
var zipcode = params.zipcode;
var Apartment = Parse.Object.extend("Apartment");
var apartment = new Apartment();
apartment.set("name", name);
apartment.set("address", address);
apartment.set("city", city);
apartment.set("state",state);
apartment.set("zipcode", zipcode);
apartment.set("map", map);
console.log(apartment);
apartment.save(null, {
success: function(savedApartment){
console.log("Succesfully saved bitch");
response.success(savedApartment);
}, error: function(error){
console.log(error);
response.error(error);
}
})
});
could you double check your server where you define the cloud code?
Your code should be something along this line:
Parse.Cloud.define("registerApartment", function(req,res){
---your codes---
});
Make sure that your Parse.Cloud.run() is calling what you defined back at your server.
Edit:
Try to use this code instead of your current one:
Parse.Cloud.run("registerApartment",{name:name,address:address,city:
city, state: state,zipcode:zipcode,map:map}, {
success: function(savedApartment){
console.log(savedApartment);
}, error: function(error){
console.log(error);
}
})
All i did was remove the quotes when parsing in a parameter. This should work fine :)

Authenticate user and add them DB simultaneously

I want to signup new users (through auth) and then add them (with their names and other info) to my user list database in realtime DB. I can't figure out what I'm doing wrong. Authentication works great but the new user is not being added to the DB.
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
in the code below, I register them then add their names to the DB and then send a verification email.
function handleRegister() {
var ref = firebase.database().ref();
console.log(email);
console.log(fname);
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
var uid = firebase.auth().currentUser.uid;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
firebase.auth().onAuthStateChanged(user => {
if(user) {
var postData = {
Fullname: fname + lname,
email: email,
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/Users/' + uid ] = postData;
return firebase.database().ref().update(updates);
}
})
} else {
console.log(error);
}
})
Authentication and send email verification works fine but names are not being added to the DB. Also if there is a better approach to achieve auth,add to DB and send email verification, please let me know. Please help.
This is the updated addition
var addusertoDB = function(user){
var uid = firebase.getAuth().uid;
var postData = {
Firstname: fname,
Lastname: lname,
email: email,
}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('Users').push().uid
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/Users/' + newPostKey] = postData;
// updates['/user-posts/' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
and handle register has been updated to
firebase.auth().createUserWithEmailAndPassword(email, password).then(
addusertoDB).catch(handleCreateUserError);
it's finally being added to the DB (without the uid) but firebase.getAuth().uid is not getting the uid. the error I'm getting is "firebase.getAuth is not a function"
You are trying to handle both the errors and the user update in the same function you have passed to catch(). This means that any code inside that function is only run when firebase.auth().createUserWithEmailAndPassword(email, password) fails.
From the firebase documentation:
createUserWithEmailAndPassword
createUserWithEmailAndPassword(email, password) returns
firebase.Promise containing non-null firebase.User
Creates a new user account associated with the specified email address
and password.
On successful creation of the user account, this user will also be
signed in to your application.
This means that on the successful creation of a user you will have access to the new user via a callback passed into then().
You probably want something like this:
var doSomethingWithNewUser = function(user) {
// Manipulate the newly created User however you like here.
// You don't have to sign them in again.
};
var handleCreateUserError = function(error) {
var errorCode = error.code;
var errorMessage = error.message;
// Do whatever you want with the error codes.
};
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(doSomethingWithNewUser)
.catch(handleCreateUserError);

Categories

Resources