how to automatic go to athor page, when success create account and set value at firebase database - javascript

i want make system, after success create an account and set value on Firebase database, it will go to the other page. i has set go to next page but, not set value into database. the think is, i want to make sure after create and set value to database and the system will move to another page.
var email = document.getElementById("email_field");
var password = document.getElementById("password_field");
firebase.auth().createUserWithEmailAndPassword(email.value, password.value).then(function(user)
{
var user = firebase.auth().currentUser;
if (firebase.auth().currentUser !== null)
console.log("user id: " + firebase.auth().currentUser.uid);
LogUser(user.uid);
console.log("user id: " + user.uid);
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorCode+"message"+errorMessage);
if(err = null){
}
// ...
});
function LogUser(user){
firebase.database().ref('tbluser').child(user).set({
email: email,
test:"ha"
});
location.replace("signin.html")
}
}

Check out the article here on how to use Firebase Database callbacks.
Your code should look something like this:
firebase.database().ref('tbluser').child(user).set({
email: email,
test: "ha"
}, function(error) {
if (error) {
// it failed, do something here
} else {
// Data saved successfully!
location.replace("signin.html")
}
})
Good luck!

Related

How to Retrieve User UID After They Have Been Created Firebase JS

I am trying to retrieve the UID of a user I just created in Firebase using JavaScript. Below is my current code:
firebase.auth().createUserWithEmailAndPassword(email, pass).catch(function(error, data) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
newusercreateduuid = data.user.uid;
// ...
console.log(errorCode + ' Error Message: ' + errorMessage);
});
I have tried a variety of callbacks including userData, data, user, and many more, but they all return null. I cannot seem to find anything online. I did find another Stack Overflow post using userData, but that returned null for me. How can I retrieve the UID of the user I just created?
you need to add this:
You can access to the then method:
firebase.auth()
.createUserWithEmailAndPassword(email, password)
.then(function(user)
// user information is available here...
})
.catch(function(error, data) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
newusercreateduuid = data.user.uid;
// ...
console.log(errorCode + ' Error Message: ' + errorMessage);
});
Also, if you need to control the user log changes, you can do this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});
This will give you the user state after login. Source

Retrieving Firebase Child Value in Javascript

function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid);
if (adaRef.orderByChild("Role").equalTo("admin")) {
location.href = "DB.html";
} else {
location.href = "index.html";
}
}
I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination I've amended your code and put it below
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
return snapshot.forEach(snapshot=>{
if (snapshot.child("Role").val()==="admin") {
location.href = "DB.html";
} else {
location.href = "index.html";
}
return console.log("added");
})
})
}
If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
//you now have all the users that are just admins
return snapshot.forEach(snapshot=>{
location.href = "DB.html";
return console.log("added");
})
})
}

I need a way to break this loop or an alternative way to do this

I'm new to js and firebase. I'm trying to use firebase database for a custom login by using my own table called users. I have used a for each loop to go through the data. But the else part is executed multiple time because of this. I need to break the loop so it won't happen.
This is my data:-
{"users" : [ {
"userId" : "1",
"username" : "admin",
"password" : "admin",
"type" : "admin"
}, {
"userId" : "2",
"username" : "cashier",
"password" : "cashier",
"type" : "cashier"
}]
}**
This is the code I wrote:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users = childSnapshot.child('username').val();
var pass=childSnapshot.child('password').val();
if(txtuser==users && txtpass==pass){
var type=childSnapshot.child('type').val();
if(type=="admin"){
location.href="admin.html";
}
else if(type=="cashier"){
location.href="cashier.html";
}
}
else{
error=true;
}
});
});
if(error==true)
{
window.alert("Invalid Credentials");
location.href="index.html";
}
}
Password Authentication
Instead of using your method of storing authentication details in the database, use the Sign in a user with an email address and password flow.
However, because you are using usernames not emails, append your storage bucket domain to the username (which will normally be PROJECT_ID.appspot.com).
So your "admin" and "cashier" users would become "admin#PROJECT_ID.appspot.com" and "cashier#PROJECT_ID.appspot.com". For the sake of email authentication, these are valid email addresses, even though they don't have inboxes.
You can then use firebase.auth() across your web app to manage your user's access control to pages like "admin.html" and "cashier.html".
Note: If you ever send out email to your users, make sure to omit emails that match "*#PROJECT_ID.appspot.com"
Answering the question
WARNING: Do not authenticate this way. Please use above method.
Passwords should never be stored in plain text
Passwords should never be stored in plain text
Users should never have access to another user's credentials in any database
For the sake of answering the question, you could use the following code:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
firebase.database().ref('users').orderByChild('username').equalTo(txtuser).once('value')
.then(function(snapshot) {
if (!snapshot.hasChildren()) {
throw "username not found";
} else if (snapshot.numChildren() != 1) {
throw "duplicate usernames";
}
// only one child at this point, so only called once
snapshot.forEach(function(childSnapshot) {
if (pass != childSnapshot.child('password').val()) {
throw "password mismatch";
}
var type=childSnapshot.child('type').val();
if(type=="admin") {
location.href = "admin.html";
} else if(type=="cashier") {
location.href = "cashier.html";
} else {
throw "unknown user type";
}
})
})
.catch(function(error) { // catches any errors thrown by promises
location.href = "index.html";
});
}
In the above code, each throw is caught by the Promise returned by the Firebase query. You can read up on Promises here.
Just check if error is set to true inside the .forEach and use return to "break" out:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users, pass;
if (error) { return; } // <-- "break" the "loop"
users = childSnapshot.child('username').val();
pass = childSnapshot.child('password').val();
if(txtuser == users && txtpass == pass){
var type=childSnapshot.child('type').val();
if(type == "admin"){
location.href="admin.html";
}
else if(type == "cashier"){
location.href="cashier.html";
}
} else {
error = true;
}
});
if(error) {
window.alert("Invalid Credentials");
location.href="index.html";
}
});
}

FIrebase jQuery .on method is updating array values one by one rather than all at once

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. For this, I used the jQuery .on method. However, this returns the values in the array that I generated for the orders one by one rather than all at once. Is this just an issue with firebase or is it just my code.
Here is my code:
When I get the values:
firebase.database().ref('Orders/' + user_id).on('value', function(snapshot) {
// Check if the user has any pending orders
if (snapshot.val() === null) {
// No Pending Orders are Present
$('.order_content-parent').html(' <div class="order_content">Hooray! You have no pending orders!</div>');
} else {
// One or more pending orders are present
console.log(snapshot.val());
snapshot.forEach(function(child){
$('.order_content-parent').html(' <div class="order_content"></div>');
var order = child.val().Order;
var key = child.key;
console.log('Key is : '+key);
getOrders(key);
});
When I insert the values into the database:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var myId = user.uid;
const orders = ['Orders: '];
$('.postData').each(function() {
var data = $(this).html();
orders.push(data);
var database = firebase.database();
database.ref('Orders/' + user_id + '/' + myId).set({
Order: orders
}, function(error) {
if (error) {
// The write failed...
alert(error);
} else {
$('.postData').html('Connecting...');
}
});
database.ref('Orders/' + myId).set({
Order: orders,
For: user_id
}, function(error) {
if (error) {
// The write failed...
alert(error);
} else {
$('.postData').html('Order Successfully Placed!');
}
});
});
} else {
// No user is signed in.
}
});
Here is my console when I print the values from the database:
Here is my database structure:
Can anyone help
Thanks in advance,
Tom
I think this is expected behaviour, as the documentation states:
The value event is called every time data is changed at the specified database reference, including changes to children.
Since your inserts are on a each loop, they get inserted one by one, triggering the .on() listener multiple times.
You could try inserting all the orders at once. Please try this approach and let me know if it works:
firebase.auth().onAuthStateChanged(function (user) {
if (!user) {
console.log("No user is signed in");
return;
}
var myId = user.uid;
var orders = [];
// Get the orders to insert first
$('.postData').each(function () {
var data = $(this).html();
orders.push(data);
});
// Then, insert them all at once
var database = firebase.database();
database.ref('Orders/' + user_id + '/' + myId).set({
Order: orders
}, function (error) {
if (error) {
// The write failed...
alert(error);
return;
}
$('.postData').html('Connecting...');
database.ref('Orders/' + myId).set({
Order: orders,
For: user_id
}, function (error) {
if (error) {
// The write failed...
alert(error);
return;
}
$('.postData').html('Order Successfully Placed!');
});
});
});

Firebase data is not updated properly

The problem : the data always get updated into 4350,
And the alert keep's pop-up-ing.
The code:
// Get no antrian function
function getNoAntri(tipe, username, name) {
// Define firebase URL
var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Log firebase URL
console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Warn user that this fiture need internet
alert('Fitur ini membutuhkan internet untuk mengambil data');
// Confirmation
alert("Mohon konfirmasi ulang");
var nama = prompt("Masukan nama"),
nik = prompt("Masukan NIK:");
if (nama != "" || nik.length != 16) {
var pasien = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + '/pasien/');
// Initialize data
faskesRef.on("value", function(snapshot) {
// Update variables
var data = snapshot.val().antrian,
one = 1,
sum = data + one;
// Update nomor antrian
faskesRef.update({
nama: name,
antrian: sum
});
// Print data
alert('No antrian: ' + snapshot.val().antrian);
// Push data to firebase
pasien.push().set({
nama: nama,
nomor_antrian: snapshot.val().antrian
})
});
} else {
// Error message
alert("Input anda tidak valid. \n Anda tidak bisa mendapatkan nomor antrian");
}
}
I've try many ways, but the code still never work.
Sorry If I doesn't ask a proper question btw
It's a bit unclear what your problem is, but an educated guess is that it boils down to this fragment of your code:
// Push input value to firebase
pasien.push().set({
nama: nama,
nik: nik,
lokasi: lokasi
});
window.location.href = 'option/' + 'available.html';
Writing data to Firebase is an asynchronous operation. Calling set() starts that operation, but by the time the set window.location, the write operation won't be done yet.
The solution is to wait for the write operation to complete before navigating away, which you can do by using a Firebase completion listener:
// Push input value to firebase
pasien.push().set({
nama: nama,
nik: nik,
lokasi: lokasi
}, function(error) {
if (!error) {
window.location.href = 'option/' + 'available.html';
}
else {
// TODO: handle error
}
});

Categories