node.js and ejs variable not showing at page refresh - javascript

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);
});
});
});
});

Related

How can I get auto ids for get nested data in firebase using javascript?

I have nested firebase data and in this data I have auto generated ids but I need to take child node's data of this auto generated ids and I have to use these ids in my query. I need to take ordersTerminal/kullanicilarTerminal/userIds(auto generated)/orderIds(auto generated)/isim/username I need to follow that path actually but I can't figure out. How can I make? Here my firebase database:
And here my javascript code:
function userConfig() { 
var dataRef = firebase.database().ref('ordersTerminal').child("kullanicilarTerminal");
dataRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
console.log(childData);
});
});
}
To get the userId of the currently logged in user, you can do the following:
let user = firebase.auth().currentUser;
let uid = user.uid;
To get the autogenerated id, you can do the following:
dataRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
var key = childSnapshot.key;
console.log(childData);
});
});
Your reference is at node kullanicilarTerminal, if you use the property key inside the forEach, you will get the following id 93ybLDezrCW2pJsDkZbH6IJfq03
If 93ybLDezrCW2pJsDkZbH6IJfq03 is the id of the currently logged in user, then you can do the following:
dataRef.child(uid).on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
var key = childSnapshot.key;
console.log(childData);
});
});
Now childSnapshot.key will return 01032020-05032020-2
If you dont have both ids, then you can get the data by doing the following:
dataRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(orderSnapshot) {
console.log(orderSnapshot.key); //01032020-05032020-2
console.log(orderSnapshot.val());
})
})
});
});
Your reference is at node kullanicilarTerminal, if you use the property key inside the first forEach, you will get the following id 93ybLDezrCW2pJsDkZbH6IJfq03, then you do another for loop and retrieve the second id 01032020-05032020-2 and the details using val().

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.

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:

How do I make a function return data that was set within function (child snapshot) in firebase

I want to return data to function that calls a function with firebase code, because of the asynchronous and nested structure of firebase queries it is not able to return values, I intend to use this logic to set tool tips in chart.js
Here is my code:
window.onload = function() {
get_data();
}
function get_data() {
var data = get_val();
console.log("...." + data);
}
function get_val() {
var label = "10/2/2017";
var Name = localStorage.getItem("VName");
console.log("Name:::" + Name);
var at_val;
var dbref = new Firebase("https://apraisalstaging.firebaseio.com/EmployeeDB/EInfo/");
dbref.once("value").then(function(snapshot) {
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
var Nameval = data.Name;
if (Nameval == Name) {
console.log("Success");
Ikey = childsnapshot.key();
console.log("Key:::" + Ikey);
var dxRef = new Firebase("https://apraisalstaging.firebaseio.com/EmployeeDB/EApraise/" + Ikey);
dxRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
console.log(data);
if (label == data.Dateval) {
console.log("-------> bingo");
at_val = data.Attitude;
console.log("got value:" + at_val);
}
});
}).then(function() {
console.log("In then:" + at_val);
return at_val;
});
}
})
})
}
Data is loaded from the Firebase Database asynchronously. You cannot return a value now that hasn't been loaded yet. And until the async and await keywords are commonplace, you cannot make JavaScript wait for the async value.
The closest you can get today is to return a promise from get_val(). Then your calling code will be:
get_val().then(function(data) {
console.log("...." + data);
});
To do this you'll have to implement get_val() as:
function get_val() {
var label = "10/2/2017";
var Name = localStorage.getItem("VName") || "delta";
console.log("Name:::" + Name);
var at_val;
var dbref = firebase.database().ref("EmployeeDB/EInfo/").orderByChild("Name").equalTo(Name);
return dbref.once("value").then(function(snapshot) {
var promises = [];
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
var Nameval = data.Name;
Ikey = childsnapshot.key;
var dxRef = firebase.database().ref("EmployeeDB/EApraise/" + Ikey).orderByChild("Dateval").equalTo(label);
promises.push(
dxRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childsnapshot) {
var data = childsnapshot.val();
at_val = data.Attitude;
});
}).then(function() {
console.log("In then:" + at_val);
return at_val;
})
);
})
return Promise.all(promises);
})
}
I made a few changes to get_val():
it uses the new 3.x versions of the Firebase SDK. The solution could also work with 2.x, I just didn't feel like setting up a jsbin for that.
it populates a list of promises, one for each of the EApraise records
it returns a promise that resolves when all the EApraise records are loaded.
it uses Firebase queries to find the correct record. This removes the need for checking the values in the then() callbacks. But more importantly it ensures that only the necessary data is downloaded.
To make that last point true, you need to add a few index definitions to the rules in your Firebase Database console:
{
"rules": {
"EmployeeDB": {
"EInfo": {
".indexOn": "Name"
}
"EApraise": {
"$eid": {
".indexOn": "Dateval"
}
}
}
}
}
Here a jsbin with the working code: http://jsbin.com/jawamilawo/edit?js,console

Categories