I'm programming my Login module so that when the user enters the username and password, it will get the input and process it in the javascript. I used the .forEach function so that the username and password will look for its matching user and store it's unique key in the GLOBAL VARIABLE so that I can use it later for data manipulation for the logged in user.
First, I declared the variable currentKey outside the the function.
var currentKey = "";
then the login function, looks like this:
function logIn(){
var loggedUname = $("#loginUname").val();
var loggedPword = $("#loginPword").val();
var tailorRef = firebase.database().ref('tailors');
tailorRef.on('value', function(data){
data.forEach(function(childData){
if ( (loggedUname == childData.val().tUsername) && (loggedPword == childData.val().tPassword) ){
currentKey = childData.key;
}
});
alert(currentKey);
});
}
If I press the login button after entering the registered username and password, it displays the corresponding key via alert.
But when I place the alert(currentKey);
outside the .on() method like this:
tailorRef.on('value', function(data){
data.forEach(function(childData){
if ( (loggedUname == childData.val().tUsername) && (loggedPword == childData.val().tPassword) ){
currentKey = childData.key;
}
});
});
alert(currentKey);
...the currentKey is displayed as UNDEFINED!
I tried making a set function inside the .forEach , but it's still the same. I'm guessing that the unique key is not stored properly in the global variable currentKey.
Anyone knows what's happening in my code?
EDIT: Sorry that I didn't state my main problem here earlier. What I want is for the key inside the .forEach to be stored in the global var currentKey, so that when I alert outside the function, the key will still be there at the var currentKey. My plan is to use the stored key in other functions in my javascript, not just inside the logIn() function. So I thought declaring the var outside the function will make it globally usable and updatable. How do I make the corresponding key to be globally usable in my javascript file?