0

I'm trying to get the value from specific child in firebase and as I see it there is nothing wrong with the code.

When I create an alert inside reciverbitconvalue menu it works but when I pass it through another string and make an alert for that string it doesn't work, it says it's undefined.

For example please check reciverbitconvalue and you will realize I passed snapshoot to another string called passbitcoin and then I passed it to an alert and when I run it it says it's undefined.

var senderbitcoinvalue;
var formbitcoinamount;
var formbitcoinuid;
var subtractbitcoin;
var passbitcoin;
var passbrecevier;
var divisionbitcoin;

document.getElementById("sendbitcoin").addEventListener("click", function() {
  //form values
  formbitcoinamount = document.getElementById("bitcoinamount").value;
  formbitcoinuid = document.getElementById("bitcoinuid").value;

  var senderbitcoinvalue = firebase.database().ref().child("users").child(uid).child("bitcoin");
  senderbitcoinvalue.on('value', function(databasesnapshot) {

    //pass bitcoin
    passbitcoin = databasesnapshot.val();

  });

  var reciverbitconvalue = firebase.database().ref().child("users").child(formbitcoinuid).child("bitcoin");
  reciverbitconvalue.on('value', function(databasesnapshot122) {

    //pass bitcoin
    passbrecevier = databasesnapshot122.val();

  });

  if (passbitcoin > formbitcoinamount) {
    subtractbitcoin = passbitcoin - formbitcoinamount;

    // put subtracted amount on sender value
    var senderbitcoinsub = firebase.database().ref();
    senderbitcoinsub.child("users").child(uid).child("bitcoin").set(subtractbitcoin);

    //reciver value
    alert(passbrecevier);
    alert("Your amount successfully been transferred");
    return;
  } else {
    alert("You dont have enough Bitcoins");
  }
});
alando
  • 3
  • 4
  • You should also look into [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) (`passbitcoin` and `passbrecevier` are set long after the rest of your code runs, since the `.on('value')` stuff happens at some point in the future, not right away. –  Sep 17 '18 at 13:23
  • i really didn't understand please explain more what you mean that they are set long reset of your code runs thank you – alando Sep 17 '18 at 13:29
  • Here's basically what you're doing: https://jsfiddle.net/khrismuc/x3mvh0L6/ In a nutshell: your code doesn't run in the order you think it runs. It's the most famous beginner's hurdle with JS and keeps coming up multiple times per day. –  Sep 17 '18 at 13:39
  • thank you I understand now – alando Sep 17 '18 at 13:51

0 Answers0