I am trying to fetch the data for website using java script.
Problem I am getting is that I am unable to get the key of
Users-->Customers-->Key-->(name, phone).
I am unable to find a syntax of it
Code I am trying is
var fireheading = document.getElementById("fireHeading");
var firebaseHeadingRef = firebase.database().ref().child("Users").child("Customers").child(uid).child("name");
firebaseHeadingRef.on('value', function(datasnapShot){
fireHeading.innerText = datasnapShot.val();
});
To get data from Firebase in javascript, you would do this:
var fireHeading = document.getElementById("fireHeading");
// "key" is the customer key
var ref = firebase.database().ref("Users/Customers/" + key);
ref.once("value", function(snapshot){
// Contains all data from Firebase
var data = snapshot.val();
// Has customer name
var customerName = data.Name;
// Has customer phone
var customerPhone = data.Phone;
// Append data to view
fireHeading.innerText = customerName;
});
This should work.
Related
what would make this work so that when the user types the correct tobedeleted value, the database deletes corresponding key with entered name?
function remove(){
var nameInput=document.getElementById("nameInput");
var database = firebase.database();
var tobedeleted = document.getElementById("tobedeleted").value;
var rootRef = database.ref("information");
var query = rootRef.orderByKey();
//gets generated keys
query.once("value",function(snapshot){
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key;
var val = childSnapshot.val();
console.log(val.name);
console.log(tobedeleted);
if (val.name===tobedeleted /*edited from val.name.equalTo(tobedeleted)*/)
{
rootRef.child("information/"+key).remove();
}
});
});
Found the solution: just changed ("information/"+key) to (key)
I'm trying to retrieve the id of the element that I inserted in the database with .key. However, it returns the user value instead of the auto-generated id.
How can I get the auto-generated id ?
var mainText = document.getElementById("main-text");
var emailText = document.getElementById("emailtxt");
var prenom = document.getElementById("prenomtxt");
var submitBtn = document.getElementById("submitBtn");
var heading = document.getElementById("heading");
var firebaseHeadingref = firebase.database().ref().child("titre");
firebaseHeadingref.on('value', function(datasnapchot){
heading.innerText = datasnapchot.val();
})
function submitClick(){
var firebaseref = firebase.database().ref();
var messageText = mainText.value;
var txtmail = emailText.value;
var prenomtxt = prenom.value;
if(messageText == "" || txtmail == "" || prenomtxt == ""){
alert("Tous les champs doivent être remplis");
return;
}
firebaseref.child("user").push().set({name : messageText, prenom:prenomtxt ,email : txtmail});
var f = firebase.database().ref().child("user").orderByChild("email").equalTo(txtmail);
// firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
//
// console.log(pushed_user.key);
//
// });
f.on("value", function(datasnapchot){
var id = datasnapchot.val();
console.log(id);
});
// location.reload();
}
There is a console notice:
It looks like you're using the development build of the Firebase J5 SDK. When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use. For the CON builds, these are available in the following manner (replace ‹PACKAGE> with the name of a component - 1.8. auth, database, etc):
https://www.gstatic.com/firebasejs/5.0.0/firebase-‹PACKAGE›.js
Try calling it like a function:
var id = datasnapchot.key();
When you push an element you can directly retrieve the auto generated ID without having to call a listener.
firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
console.log(pushed_user.key);
});
You can find another example here.
var newPostKey = firebaseref.child("user").push().set({name : messageText,prenom:prenomtxt ,email : txtmail}).key;
"newPostKey" will be your key
Try the following:
var ref = firebase.database().ref("users");
ref.push().on("value", function(snapshot) { snapshot.forEach(function(childSnapshot) {
var id = childSnapshot.key();
console.log(childSnapshot);
});
});
You need to loop using forEach and then you will be able to retrieve the push key using key()
This worked for me
var id = datasnapchot.key;
Use datasnapchot.key instead of datasnapchot.key()
I'm new to Firebase functions and trying to understand how to get a certain key from the database .onCreate trigger. Here is an example:
exports.createUserRoundData =
functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var eventData = event.data.val();
var userKey = event.params.user_key;
var itemKey = eventData.items; // This returns an object
});
The structure is:
players > user_key > items > item_key > data
In the above scenario how can I retrieve the item_key?
Yes you can,
You need something like this :
exports.createUserRoundData = functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var userKey = event.params.user_key; // Get user key parameter
var eventSnapshot = event.data; // Get player data
var itemsSnapshot = eventSnapshot.child('items'); // Get items data
itemsSnapshot.forEach(function(itemSnapshot) { // For each item
var itemKey = itemSnapshot.key; // Get item key
var itemData = itemSnapshot.val(); // Get item data
});
});
Here the Firebase Cloud Functions documentation.
I am new to Ionic / Firebase and I try to update fields via a form. Everything works, no error, all console log show up what needed but the data are not being updated in the database.
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
function writeUserData(name, description) {
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
}
$state.go("tab.account");
});
Any idea ? Or maybe a better method to simply update firebase's database via a form when the user is logged in ?
Seems you didn't really don't know the real significance/uses of function yet about when to use it
Well it's because you wrap it inside writeUserData and which is you didn't event execute/call this function
Also function writeUserData isn't necessary in this situation
so remove function it
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
});
You just transfer $state.go("tab.account"); to receiveNewData
Edited
To be able to catch the changes just call add child_added event listener inside 'accounts/' + userId
function receiveNewData() {
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
// Creates local "temporary" object for holding employee data
var newTrain = {
tname: trainName,
dest: destination,
firstTime: firstTrainTime,
freq: frequency
};
// Uploads train data to the database
trainDataBase.ref().push(newTrain);
THIS IS THE PART I CAN"T figure out how do I get a key for the object I just created on the server? I tired the below but it comes back undefined, also also tired var = newKey = trainDatabase.ref.push(newTrain).key but then it creates to object versus one but I do get a key
// newKey = trainDataBase.ref(newTrain).key
// console.log("nodeKey" , newKey)
// Alert
console.log("train successfully added");
// Clears all of the text-boxes
$("#trainName").val("");
$("#destination").val("");
$("#firstTrainTime").val("");
$("#frequency").val("");
// Prevents moving to new page
return false;
});
Perhaps there's a better way, but I've used this to make it work:
var trainDataBaseRef = trainDataBase.ref().push();
trainDataBaseRef.set({
id: trainDataBaseRef.key,
// rest of object data
});
Take a look at their docs for an additional way to do this (Updating or deleting data section):
function writeNewPost(...) {
var postData = {
// data
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}