'db is undefined' problem with firebase integration in JS - javascript

I am doing a small contact form on my personal website. I have a problem with integration of firebase database with form. I read the documentation and watched some YT tutorials and I cannot find the mistake. Could you please take a look? I get a 'db is undefined' error in console.
window.onload = function() {
var firebaseConfig = {
apiKey: "sampleValue",
authDomain: "sampleValue",
databaseURL: "sampleValue",
projectId: "sampleValue",
storageBucket: "sampleValue",
messagingSenderId: "sampleValue",
appId: "sampleValue",
measurementId: "sampleValue"
};
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore;
function submitForm() {
// e.preventDefault();
let nameEl = document.getElementById("InputName");
let emailEl = document.getElementById("InputEmail");
let subjectEl = document.getElementById("InputSubject");
let messageEl = document.getElementById("InputMessage");
let nameValue = nameEl.value;
let emailValue = emailEl.value;
let subjectValue = subjectEl.value;
let messageValue = messageEl.value;
db.collection("contact").doc().set({
name: nameValue,
email: emailValue,
subject: subjectValue,
message: messageValue
})
.then(function() {
alert("dataSaved");
})
.catch(function() {
alert("error");
});
}
document.getElementById("submit").addEventListener("click", submitForm());
};
Edit
I have managed to solve the problem thanks to fellow users #Kevin Peña and #Phix help by:
putting the missing firebase-firestore.js script in index.html
<script defer src="https://www.gstatic.com/firebasejs/7.12.0/firebase-firestore.js"></script>
I had realized that settings in my DB disallowed me to push anything from my form so I have changed the rules to
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}

Expanding a bit on Phix's comment. Right here:
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore; // <- here
It should be
let db = firebase.firestore()
You can find this on the Guides and on the Reference.
Also, here:
document.getElementById("submit").addEventListener("click", submitForm() /* <-over here */);
You should not call the function, instead pass it to addEventListener (i.e. just its name)
document.getElementById("submit").addEventListener("click", submitForm);
Otherwise the form will be submitted empty when the page loads. And nothing will happen on button click.

Related

firebase is not defined, database.ref() is not a function

i have this issue of 'firebase is not defined' when i try to read and display data from the relatime database.
I am using firebase to host a simple site in which you input 4 values and receive a score back, everything is scored in the database. i then want to display the highest 10 scores from the database, and im having trouble doing that.
Ive seen lot of people having this issue, but their resolutions are not working for me
Here is my code
function displayTopScores() {
// Reference to the scores in the database
var scoresRef = firebase.database().ref("scores");
// Retrieve the top 10 scores
scoresRef.orderByChild("Score").limitToFirst(10).on("value", function(snapshot) {
var scores = snapshot.val();
// Array to store the top 10 scores
var topScores = [];
// Add the scores to the array
for (var score in scores) {
topScores.push(scores[score]);
}
// Sort the scores in descending order
topScores.sort(function(a, b) {
return b.Score - a.Score;
});
// Create a table to display the scores
var table = document.createElement("table");
table.setAttribute("class", "table table-striped");
// Add a header row to the table
var headerRow = table.insertRow(-1);
var nameHeaderCell = headerRow.insertCell(-1);
nameHeaderCell.innerHTML = "Name";
var scoreHeaderCell = headerRow.insertCell(-1);
scoreHeaderCell.innerHTML = "Score";
// Add a row for each score
for (var i = 0; i < topScores.length; i++) {
var row = table.insertRow(-1);
var nameCell = row.insertCell(-1);
nameCell.innerHTML = topScores[i].Name;
var scoreCell = row.insertCell(-1);
scoreCell.innerHTML = topScores[i].Score;
}
// Add the table to the HTML page
var scoresContainer = document.querySelector("#scores-container");
scoresContainer.innerHTML = "";
scoresContainer.appendChild(table);
});
}
const dbRef = ref(getDatabase());
get(child(dbRef, `scores/Scores`)).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});
i have imported (i think) all the right things for this to happen, but i am clearly doing some mistake i have not figured out.
here is what i import:
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "---",
authDomain: "---",
databaseURL: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
import {getDatabase, set, get, update, remove, ref, child}
from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const database = getDatabase();
I've read the documentation on how to import the database and app function, looked at other people with the same issue, tried to ask openAI but with no luck.
tried using different ways of creating a reference and read the data.
You need to pass the app variable as a parameter to getDatabase() it should be getDatabase(app)
Here is the official code from the firebase documentation:
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
// ...
databaseURL: "https://DATABASE_NAME.firebaseio.com",
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
You can follow further examples from the documentation here: https://firebase.google.com/docs/database/web/start#web-version-9
function displayTopScores() {
const dbRef = ref(getDatabase());
get(child(dbRef, `scores/`)).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
document.getElementById("scores-list").innerHTML = console.log(snapshot.val());
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});
}
its not complete solution cause i still cant show in my site the values from the database, but this seems to fix the issue at least in part, now i see the database getting read from the chrome dev tool

Create user with Phone number Firebase [duplicate]

I've been googling for 2 days for html and JavaScript code for adding firebase phone number authentication in my website.
I saw the firebaseui doing this job.
But it has their own form elements.
I haven't found any articles or videos showing "how to make Firebase web auth with phone number, without using Firebaseui/nodejs.
Is it really possible to do this with my own textbox and other buttons?
I had written a code for this and it's not working.
Please do a checkup or prefer any best articles, showing the exact thing I want.
The code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Untitled</title>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "*****",
authDomain: "********.firebaseapp.com",
databaseURL: "https://********.firebaseio.com",
projectId: "*******",
storageBucket: "*********.appspot.com",
messagingSenderId: "**********"
};
firebase.initializeApp(config);
</script>
</head>
<body>
<script>
var phoneNumber = getPhoneNumberFromUserInput();
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
alert('sms sent');
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
}).catch(function (error) {
// Error; SMS not sent
// ...
alert('sms not send');
});
</script>
<form>
<input type="tel" id="number">
<input type="number" id="otp_code">
<input type="submit">
</form>
</body>
</html>
Thanks in advance.
There are a lot of examples including the Firebase GitHub sample quick start apps: https://github.com/firebase/quickstart-js/blob/master/auth/phone-invisible.html
Also check the official docs on this: https://firebase.google.com/docs/auth/web/phone-auth
Here is a quick snippet on signing in a user with phone number:
firebase.auth().signInWithPhoneNumber("+xxxxxxxx", window.recaptchaVerifier)
.then((confirmationResult) => {
// At this point SMS is sent. Ask user for code.
let code = window.prompt('Please enter the 6 digit code');
return confirmationResult.confirm(code);
})
.then((result) {
// User is now signed in and accessible via result.user.
});
.catch((error) => {
// Error occurred.
});
# Try This Code. I have only add js/jquery code#
<script>
// Paste the config your copied earlier
var firebaseConfig = {
apiKey: "############################",
authDomain: "############################",
databaseURL: "############################",
projectId: "############################",
storageBucket: "############################",
messagingSenderId: "############################",
appId: "############################",
measurementId: "############################"
};
firebase.initializeApp(firebaseConfig);
// Create a Recaptcha verifier instance globally
// Calls submitPhoneNumberAuth() when the captcha is verified
//set size: "normal" to add recaptcha
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
"recaptcha-container",
{
size: "invisible",
callback: function(response) {
submitPhoneNumberAuth();
}
}
);
// This function runs when the 'sign-in-button' is clicked
// Takes the value from the 'phoneNumber' input and sends SMS to that phone number
function submitPhoneNumberAuth() {
$("#wait").css("display", "block");
$("#sign-in-button").attr("disabled", true);
var userPhone = document.getElementById("phoneNumber").value;
if(userPhone.length != 11){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Please Insert 11 digit Phone Number!!!");
$("#message").css("display", "block");
$("#wait").css("display", "none");
$("#sign-in-button").attr("disabled", false);
return false;
}
var phoneNumber = "+88"+userPhone;
//+88 only for bangladesh.Add your own country code
var appVerifier = window.recaptchaVerifier;
firebase
.auth()
.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function(confirmationResult) {
document.getElementById('codeDiv').style.display='block';
document.getElementById('getCodeButton').style.display='none';
window.confirmationResult = confirmationResult;
$("#message").html("Please check your inbox and insert code!!!");
$("#message").css("display", "block");
$("#wait").css("display", "none");
})
.catch(function(error) {
$("#sign-in-button").attr("disabled", false);
$("#wait").css("display", "none");
console.log(error.code);
if(error.code == 'auth/invalid-phone-number'){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Invalid Phone Number!! Try Another Number!!!");
$("#message").css("display", "block");
document.getElementById('getCodeButton').style.display='block';
document.getElementById('codeDiv').style.display='none';
}
else if(error.code == 'auth/too-many-requests'){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Too many request from this number. Try Another Number!!");
$("#message").css("display", "block");
document.getElementById('getCodeButton').style.display='block';
document.getElementById('codeDiv').style.display='none';
}
});
}
// This function runs when the 'confirm-code' button is clicked
// Takes the value from the 'code' input and submits the code to verify the phone number
// Return a user object if the authentication was successful, and auth is complete
function submitPhoneNumberAuthCode() {
$("#wait").css("display", "block");
$('#confirm-code').attr("disabled", true);
var code = document.getElementById("code").value;
confirmationResult
.confirm(code)
.then(function(result) {
var user = result.user;
$("#wait").css("display", "block");
$("#message").removeClass("alert-danger");
$("#message").addClass("alert-info");
$("#message").html("Thank you!!Code Matched!!");
$("#message").css("display", "block");
})
.catch(function(error) {
$("#wait").css("display", "none");
$('#confirm-code').attr("disabled", false);
console.log(error);
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Code Not Matched!!!");
$("#message").css("display", "block");
});
}
//This function runs everytime the auth state changes. Use to verify if the user is logged in
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
//You are logged IN from firebase
$("#message").removeClass("alert-danger");
$("#message").addClass("alert-info");
$("#message").html("Congratulations!!!Logging...");
$("#message").css("display", "block");
var phone = user.phoneNumber;
firebase.auth().signOut().then(function() {
////You are logged Out from firebase
console.log("Firebase Signout");
}).catch(function(error) {
console.log("Firebase Signout Problem!!");
});
}

Cannot query from Firebase for my React Native app?

It seems I can retrieve all my data from my Firebase Realtime Database with the following:
let itemsRef = firebaseApp.database().ref('/');
itemsRef.on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
But when I try to query with specific parameters instead of just retrieving all the information, I always end up with this error:
#firebase/database: FIREBASE WARNING: Exception was thrown by user callback.
TypeError: Cannot convert undefined or null to object
This is how I'm trying to query information... literally following the documentation, and somehow my code works when I retrieve all information but not when the only change I make is adding a query?
let itemsRef = firebaseApp.database().ref('/');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
Is anyone else having problems querying from Firebase or am I doing something wrong?
This is how my data is structured on Firebase:
I would try initializing firebase in dbConfig.js for instance like so:
import * as firebase from 'firebase';
let config = {
apiKey: "XXXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX"
};
firebase.initializeApp(config);
export default firebase;
I would import firebase where it's:
import firebase from './dbConfig.js'
let itemsRef = firebase.database().ref('/');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
Note: OrderByChild the element roundedBPM needs to be a direct child to the root path '/' if it's a nested child you could do something like this:
let itemsRef = firebase.database().ref('/users');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
...
});
Note: if you are setting equalTo() roundedBPM when it's a number and not a string you wouldn't get back any data. Make sure you use the correct type of data.
I hope this will help!

how to send data to firebase database in function

I'm trying to send data to firebase. The data is saved to the database after the function is performed, how can I overwrite it during the function execution?
import firebase from 'firebase';
var config = {
apiKey: "xxx",
authDomain: "xxx.firebaseapp.com",
databaseURL: "https://xxx.firebaseio.com",
projectId: "xxx",
storageBucket: "xxx.appspot.com",
messagingSenderId: "xxx"
};
firebase.initializeApp(config);
var db = firebase.database();
var sleep = require('sleep');
function run(TIME) {
db.ref('/test/').child('status').set('1');
sleep.sleep(TIME);
db.ref('/test/').child('status').set('2');
sleep.sleep(TIME);
db.ref('/test/').child('status').set('3');
sleep.sleep(TIME);
db.ref('/test/').child('status').set('4');
};
//========================================<<<< Now I see status in Firebase
run(5);
The set() method is asynchronous and returns a promise that resolves when write to server is complete, as explained in the doc here.
From you comment above I understand you want to have a status "WORKING - before starting function and DONE after".
So you should do something along the following lines:
var status = '';
var adaNameRef = firebase.database().ref('users/ada/name');
status = 'WORKING';
adaNameRef.set({ first: 'Ada', last: 'Lovelace' })
.then(function() {
status = 'DONE';
})
.catch(function(error) {
console.log('Synchronization failed');
});
If you want to "write multiple values to the Database at once", you should use the update() method. See here and here.
Similarly to the set() method, the update() method is asynchronous and returns a promise that resolves when write to server is complete, so you would use the same logic to update the value of status
UPDATE following your comment
1. Send status 'WORKING' to FB 2. Set Relay to ON 3. Wait x seconds 4. Send status 'DONE' to FB 5. Set Relay to OFF
If I understood correctly, this should work (not tested however):
var adaNameRef = firebase.database().ref('users/ada/name');
adaNameRef.set({ status: 'WORKING'})
.then(function() {
// Set Relay to ON ... don't know exactly how you "set the relay"
sleep.sleep(x);
return adaNameRef.set({ status: 'DONE'})
})
.then(function() {
// Set Relay to OFF
})
.catch(function(error) {
console.log(error);
});

firebase database set funtion does not work

This is my code.here set function does not work(value is not updated in firebase database) and no error shown in console.please help me.
var config = {
apiKey: '************************************',
authDomain: 'my-app.firebaseapp.com',
databaseURL: 'https://my-app.firebaseio.com',
storageBucket: 'gs://my-app.appspot.com'
};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
rootRef.set({
'like':'5'
});
firebase database rules as follows
{
"rules": {
".read": true,
".write": true,
"learning": {
"mngmt_quote":
{
},
"Author":{
}
}
}
}
I have tried many methods found in internet.no solution found.please help me
Try this and see if what message you get.
var rootRef = firebase.database().ref();
rootRef.set({
like: '5'
}).then(success => {
console.log('success',success);
},
error => {
console.log('error',error);
}
);

Categories