How can i fetch data from realtime database using firebase v9? - javascript

I was wondering how can I fetch the data everytime I create a new guest through form using realtime database in firebase v9? I was trying to find the ways of doing it on the internet but I couldn't. So i want to fetch data from realtime database everytime i submit my form and show the data in a table. Also is there and easier way to send data than I did it here using set and ref? Thanks.
Here is the existing code:
HTML:
<body>
<form class="form">
<span>Guest name:</span>
<input type="text" name="name" id="name"><br>
<span>Guest surname:</span>
<input type="text" name="surname" id="surname"><br>
<span>Tel:</span>
<input type="number" name="tel" id="tel" maxlength="16"><br>
<span>Country:</span>
<input type="text" name="country" id="country"><br>
<span>Arrival date:</span>
<input type="date" name="arrivalDate" id="arrivalDate"><br>
<span>Departure date:</span>
<input type="date" name="departureDate" id="departureDate"><br><br>
<input type="submit" value="Send">
</form>
<p class="success"></p>
</body
jQuery:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
const firebaseConfig = {
apiKey: "hidden",
authDomain: "hidden",
databaseURL: "hidden",
projectId: "reservations-32294",
storageBucket: "reservations-32294.appspot.com",
messagingSenderId: "773498700596",
appId: "1:773498700596:web:618889de8423f066071b61"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const db = getDatabase();
function insertData() {
set(ref(db, "Guests/" + $("#name").val() + " " + $("#surname").val()), {
Name: $("#name").val(),
Surnam: $("#surname").val(),
Tel: $("#tel").val(),
Country: $("#country").val(),
ArrivalDate: formatDate($("#arrivalDate").val()),
DepartureDate: formatDate($("#departureDate").val())
})
.then(() => {
$(".success").html("Success!").fadeIn("fast");;
setTimeout(function() {
$('.success').fadeOut('fast');
}, 2000);
$("input").removeAttr("disabled");
})
.catch(error => alert(error));
}
$(".form").submit(function(e) {
e.preventDefault();
$("input").attr("disabled", "true");
insertData();
});
const formatDate = (date) => {
const newDate = date.split("-");
let day = newDate[2];
let month = newDate[1];
let year = newDate[0];
let newFormat = `${day}.${month}.${year}.`;
return newFormat;
}

You just need to read data with the get method and listen for changes with onValue method.
import { getDatabase, ref, set, get, onValue } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const db = getDatabase();
const guestsRef = ref(db, 'Guests');
onValue(guestsRef , (snapshot) => {
if (snapshot.exists()) {
const data = snapshot.val();
// Do something with your data.
}
});
Docs: https://firebase.google.com/docs/database/web/read-and-write#web_value_events

Related

Firebase realtime database record only one child

for a specific use, I would like to save in the realtime database only one element and that it is updated when it is modified, I do not need to save all the changes as child.
I have this code but it creates child.
<script type="module">
import {initializeApp} from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
import {
getDatabase,
set,
ref,
push,
child,
onValue,
onChildAdded
} from "https://www.gstatic.com/firebasejs/9.6.6/firebase-database.js";
const firebaseConfig = {
apiKey: "...",
authDomain: "....firebaseapp.com",
databaseURL: "....firebaseio.com",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "..."
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
submit.addEventListener('click', (e) => {
var message = document.getElementById('message').value;
//var name = myName;
const id = push(child(ref(database), 'messages')).key;
set(ref(database, 'messages/' + id), {
//name: name,
message: message
});
document.getElementById('message').value = "";
//alert('message has sent');
});
const dbRef = ref(getDatabase());
const newMsg = ref(database, 'messages/');
onChildAdded(newMsg, (data) => {
var divData = data.val().message;
let h1 = document.querySelector("h1");
h1.textContent = divData;
});
Thanks.
If you don't want to create a child node, you can simply write messages with:
set(ref(database, 'messages'), {
message: message
});

Is there a way to give unique id numbers to a page?

I get the data of all the movies on my home page. But I don't want to do this on the Admin.html page. On the admin page, when I click on the name of the movie, I want to go to the page related to that movie. For example, when I click on the movie "Schindler's List" which movieId is 3 (Admin.html?movieId=3), I want to go to a page with only Schindler's List movie information. It will show only Schindler List's img,score,name. How can I achieve this?
Admin.html
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import { getDatabase, set, ref, update, get, child } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);
btnCreate.addEventListener('click',(e)=>{
var movieId = document.getElementById('movieId').value;
var movieName = document.getElementById('movieName').value;
var movieScore = document.getElementById('movieScore').value;
var movieImage = document.getElementById('movieImage').value;
set(ref(db, 'Movies/' + movieId), {
movieId: movieId,
movieName: movieName,
movieScore: movieScore,
movieImage : movieImage
});
});
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name,score,img,id){
let html='';
const movies=`
<div class="content"><img src="${img}"><p>${name}</p> <p> <img src="img/mutlu.png" class="emoji"><a class="scoretxt">${score}</a> </p> </div>
`;
html = movies;
body.innerHTML += html;
body2.innerHTML+=html;
}
function AddAllItemsToTable(TheMovies){
body.innerHTML="";
TheMovies.forEach(element => {
AddItemsToTable(element.movieName, element.movieScore, element.movieImage,element.movieId);
});
}
function getAllDataOnce(){
const dbRef=ref(db);
get(child(dbRef,"Movies"))
.then((snapshot)=>{
var movies=[];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload= getAllDataOnce;

firebase.database() is not a function

Error message:
TypeError: _this.db is not a function
Code:
import app from "firebase/app";
import "firebase/auth";
import "firebase/database";
const config = {
apiKey: "some-api-key",
authDomain: "myapp.firebaseapp.com",
databaseURL: "https://myapp.firebaseio.com",
projectId: "aofndiuf",
storageBucket: "project-somenumber.appspot.com",
messagingSenderId: "793813245724y6597"
};
class Firebase {
constructor() {
app.initializeApp(config);
this.auth = app.auth();
this.db = app.database();
}
// Auth API
doCreateNewsletter = (news, name, description, email) => {
const newsletter = { news, name, description, email };
const newPostKey = this.db()
.ref()
.child("newsletters")
.push().key;
return this.db
.ref()
.child("/newsletters/" + newPostKey)
.set(newsletter);
};
You assigned this.db like this:
this.db = app.database();
But then you refer to it later like this:
const newPostKey = this.db()
...
The object returned from app.database() isn't a function, so you can't call it like a function as you are now. It's a Database object. Perhaps you can just get rid of those parenthesis to make your code work the way you intended.

.signInWithEmailandPassword is not a function

I was following this video from the Firebase Team to add Firebase Auth to my application (https://www.youtube.com/watch?v=-OKrloDzGpU)
I have added the web application script generated for my project in Firebase into the html section of my app and basically copied the other code to do the login and signing up as seen in the code below
But I got this error which I have no idea why its triggering
TypeError: auth.signInWithEmailandPassword is not a function. (In 'auth.signInWithEmailandPassword(email, pass)', 'auth.signInWithEmailandPassword' is undefined)
HTML Code
<!DOCTYPE html> <meta charset="utf-8" />
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-auth.js"></script>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" required placeholder="Email" />
<input id="txtPassword" type="password" required placeholder="Password" />
<button id="btnLogin" class="button-is-link">Login</button>
<button id="btnSignUp" class="button-is-info">Sign Up</button>
</div>
<script src="js/auth.js"></script>
</body>
</html>
Auth.js
(function() {
// Initialize Firebase
var config = {
apiKey: 'API KEY',
authDomain: 'DOMAIN',
databaseURL: 'DATABASE',
projectId: 'ID',
storageBucket: 'BUCKET',
messagingSenderId: 'ID'
};
firebase.initializeApp(config);
const txtEmail = document.getElementById('txtEmail');
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnSignUp = document.getElementById('btnSignUp');
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'));
firebase.auth().onAuthStateChange(firebaseUser => {
if (firebaseUser) {
console.log('U are logged in');
} else {
console.log('Not logged in');
}
});
});
})();
The exact method name is signInWithEmailAndPassword, with an upper case "A" at And.
It is the same with createUserWithEmailAndPassword.
run given below command, Before execute make sure to delete "package-lock.json"
npm i #angular/fire#latest --save

Login button does not work for firebase auth

I'm a newbie at firebase.
I'm trying to code a simple login page where the user logs in and then is redirected to home.html.
This is my index page:
<html>
<body>
<script src="https://gstatic.com/firebasejs/live/3.1/firebase.js"></script>
<div class="container">
<input id="txtEmail" type="email" placeholder="Email">
<input id="txtPassword" type="password" placeholder="Password">
<button id="btnLogin" class="btn btn-action">Log in</button>
<button id="btnSignUp" class="btn btn-secondary">Sign Up</button>
<button id="btnLogout" class="btn btn-action hide">Log out</button>
</div>
<script src="app.js"></script>
</body>
</html>
And this is my app.js:
(function() {
// Initialize Firebase
const config = {
apiKey: "...",
authDomain: "fir-test-bb3bd.firebaseapp.com",
databaseURL: "https://fir-test-bb3bd.firebaseio.com",
projectId: "fir-test-bb3bd",
storageBucket: "fir-test-bb3bd.appspot.com",
messagingSenderId: "509522467811"
};
firebase.initializeApp(config);
// Get elements
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');
// Add login event
btnLogin.addEventListener('click', e => {
// Get email and pass
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));
});
// Handle Account Status
firebase.auth().onAuthStateChanged(user => {
if (user) {
window.location = 'home.html'; //After successful login, user will be redirected to home.html
// Add signup event
btnSignUp.addEventListener('click', e => {
// Get email and pass
// TODO: CHECK FOR REAL EMAIL
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
// Sign in
const promise = auth.CreateUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
// Add a realtime listener
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
console.log(firebaseUser);
} else {
console.log('not logged in');
}
});
}
});
});
When i go enter a valid username and password nothing happens, when I enter an invalid username and password nothing happens. When I check the console logs there is absolutely nothing even though it should be stating what is happening.
Any idea?
Thank you again for any help.
UPDATE 1
This is the new login bit...still same problem
//Add login event
btnLogin.addEventListener('click', e => {
//Get email and pass
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
{
promise.then(onResolve, onReject)
onResolve(e => console.log(e.message));
firebase.auth().onAuthStateChanged(user => {
if(user) }{
window.location = 'home.html';
}});

Categories

Resources