How to pass firebase value/key as parameter in functions javascript - javascript

Is it possible to pass the key of where the data is located as a parameter in function?
For example;
function myfirebasedata(myDivTag, value){
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.on('child_added', function(snapshot) {
var data = snapshot.val();
myDivTag.innerHTML = data.value.age;
});
}
and then I could call this like:
myfirebasedata(divTagAgeJames, James);
myfirebasedata(divTagAgeBob, Bob);
....
....
So for example, when the first instance of the function is run/called myfirebasedata(divTagAgeJames, James);
it should replace the keywords in the reference of firebase code above to;
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.on('child_added', function(snapshot) {
var data = snapshot.val();
myDivTagJames.innerHTML = data.James.age;
});
Update:

You could try one of those:
1.snapshot.child()
ref.on('child_added', function(snapshot) {
var age = snapshot.child(value).val().age;
myDivTag.innerHTML = age;
});
2.bracket notation
ref.on('child_added', function(snapshot) {
var data = snapshot.val();
myDivTagJames.innerHTML = data[value].age;
});

Related

Trying to delete the value of key for web application through firebase

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)

Updating $scope with firebase

Im trying to update the scope after I get the response from Firebase (I am doing it in the app controler part), here is a sample code.
PS I am using AngularFire ,Firebase and Angularjs
Thank You
var app = angular.module("sampleApp", ["firebase"]);
firebase.initializeApp(config);
app.factory("mealMacros", ["$firebaseArray",
function($firebaseArray) {
var dbRef = firebase.database();
var userId = sessionStorage.uid;
var ordersRef = firebase.database().ref('user_info/' + userId + '/orders');
return $firebaseArray(ordersRef);
}
]);
app.controller("MealCtrl", ["$scope", "mealMacros",
function($scope, mealMacros) {
// $scope.user = "Guest " + Math.round(Math.random() * 100);
//tried mealMacros.on.. didnt work
ordersRef.on('value', function(snapshot) {
var orders = snapshot.val();
// Loop and parse order ids here
for (var key in orders) {
var orderId = orders[key]['orderType'];
console.log(orderId);
$scope.products = orderId;
//code not reaching here
}
});
}
]);
ordersRef.on('value', function(snapshot) {
var orders = snapshot.val();
// Loop and parse order ids here
for (var key in orders) {
var orderId = orders[key]['orderType'];
console.log(orderId);
$scope.products = orderId;
//code not reaching here
}
});
First you need to make sure you get data in var orders
Then $scope.products = orderId; you set the same variable in a loop. Maybe $scope.products is an array and you want to push data in it? $scope.products.push(orderId);
Finally, setting a $scope variable inside a .on event, you will need to call $scope.$apply() before the function returns.
ordersRef.on('value', function(snapshot) {
var orders = snapshot.val();
console.log(orders); // make sure there's an array here
for (var key in orders) {
var orderId = orders[key]['orderType'];
$scope.products.push(orderId);
}
$scope.$apply();
});
One last thing, var orderId = orders[key]['orderType']; may not work as expected depending on the structure of your var orders array.
You can try var orderId = key.orderType; if that doesn't work.

node.js and ejs variable not showing at page refresh

I'm trying to pass variable from js to .ejs template file. The values are coming at page first opening but not showing at refresh page. When I log variables, they are seem in console at every refresh.
ejs:
<input type="text" value="<%= userfb.testTarget %>" data-min="<%= userfb.testMin %>" data-max="<%= userfb.testMax %>" data-fgcolor="#157fa2" class="dial ringtarget">
app.js
var query = firebase.database().ref('/doctors/patients/' + request.id + "/testResults");
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var resultData = childSnapshot.val();
var testid= resultData.testid;
console.log("testid:"+testid);
//Setting Test Results
// Loop through users in order with the forEach() method. The callback
// provided to forEach() will be called synchronously with a DataSnapshot
// for each child:
var childData = childSnapshot.val();
console.log(childData.testResultValues);
var testResultValues =[];
for (i in childData.testResultValues) {
testResultValues.push(childData.testResultValues[i].value);
}
userfb.testResultValues=testResultValues;
console.log(testResultValues);
//Getting test informations
var testquery = firebase.database().ref('/doctors/tests').orderByChild("testID").equalTo(testid);
testquery.once("value")
.then(function(snapshot2) {
snapshot2.forEach(function(snapshot2) {
var testData = snapshot2.val();
userfb.testName=testData.testName;
userfb.testMax=testData.limitValues.max;
userfb.testMin=testData.limitValues.min;
userfb.testTarget=testData.normalValues.Female;
console.log("testmax:"+userfb.testMax);
});
});
});
});
Solution:
I divided the return values (as userfb and testInformations) for each firebase query and now working with refresh page.
var query = firebase.database().ref('/doctors/patients/' + request.id + "/testResults");
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var resultData = childSnapshot.val();
var testid= resultData.testid;
console.log("testid:"+testid);
//Setting Test Results
// Loop through users in order with the forEach() method. The callback
// provided to forEach() will be called synchronously with a DataSnapshot
// for each child:
var childData = childSnapshot.val();
console.log(childData.testResultValues);
var testResultValues =[];
for (i in childData.testResultValues) {
testResultValues.push(childData.testResultValues[i].value);
}
userfb.testResultValues=testResultValues;
console.log(testResultValues);
//Getting test informations
var testquery = firebase.database().ref('/doctors/tests').orderByChild("testID").equalTo(testid);
testquery.once("value")
.then(function(snapshot2) {
testInformations = snapshot2.val()
snapshot2.forEach(function(snapshot2) {
var testData = snapshot2.val();
testInformations.testName=testData.testName;
testInformations.testMax=testData.limitValues.max;
testInformations.testMin=testData.limitValues.min;
testInformations.testTarget=testData.normalValues.Female;
console.log("testmax:"+testInformations.testMax);
});
});
});
});

Firebase data is "undefined" when it is not

I am trying to retrieve some data from my firebase database, but the value I get is "undefined".
This is how I save the data to the database:
var database = firebase.database();
database.ref().push({
mainArray: mainArray,
secondArray: secondArray,
listname: listName,
mainLanguage: mainLanguage,
secondLanguage: secondLanguage,
}, function(error) {
if (error){
stopLoader();
showSnackbar("An error has occured! Please try again later.");
}
This is how I read the data, but the value of listname is "undefined":
var database = firebase.database().ref().child('codes');
var codeInput = document.getElementById('mainSearch');
database.on('value', function(snapshot) {
if (!snapshot.hasChild(codeInput.value)) {
codeInput.value = "";
showSnackbar("A list with this code does not exist!<br><br>Please try another one.")
}
else {
var data = snapshot.val();
var listname = data.listname;
console.log(listname);
}
});
This is the value I get from the database:
This is how the data is structured in the database:
I changed my code to this and now it works perfectly. The problem was that i was trying to get the value from the wrong child. Thanks for your help and patience!
var database = firebase.database().ref().child('codes');
var codeInput = document.getElementById('mainSearch');
database.child(codeInput).on('value', function(snap) {
var data = snap.val();
var listName = data.listname;
var mainLanguage = data.mainLanguage;
var secondLanguage = data.secondLanguage;
var mainArray = data.mainArray;
var secondArray = data.secondArray;
});

Retrieve Keys and elements of Array Firebase Database

I'm working with Firebase realtime database and I want to retrieve an array data:
Data:
And my function:
function traerUsuarios(firebase)
{
var ref = firebase.database().ref().child('/Usuario');
console.log(ref)
ref.once('value', function (snap) {
snap.forEach(function (item) {
var itemVal = item.val();
console.log(itemVal);
});
});
}
But the result:
Show me object but no de for of the items
What im doing wrong?
Each item in your for loop are the children of Usario. Each of these children (from your picture 056BN.., CQL.., and E4ll) have an object as their value (hence why they have a + next to them in the database).
So when you say item.val() you're getting the value of each one of those children, which is their corresponding object (The data you see when you click the + in the database.
Thanks to #MarksCode , I fixed the function with data refs:
function traerUsuarios(firebase) { var key;
var starCountRef;
var usuarios=new Array();
// var ref = firebase.database().ref().child('/Usuario');
var query = firebase.database().ref("/Usuario").orderByKey();
query.once("value")
.then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
// key will be "ada" the first time and "alan" the second time
key = childSnapshot.key;
starCountRef = firebase.database().ref("/Usuario/"+key);
starCountRef.on('value', function (snapshot) {
console.log(snapshot.val());
usuarios.push([key,snapshot.val()]);
});
});
}); }
And the result show me the values:

Categories