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 >
<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 ></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;
}
CodePudding user response:
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