Dharmesh Faquir
Dharmesh Faquir

Reputation: 55

Firebase Saving multiple data

I am new to using google Firebase. I have manage to add real time saving data function, but I wanted to save the data that i have. Please could someone direct me to the right path?

Here is the code in .JS file:

var btn = document.getElementById(btn);

var weight, height, measure, bmi, error ;

function calculate() {

    var firebaseRef = firebase.database().ref();

    firebaseRef.child("BMI").set("BMI Values");

    weight = document.getElementById("weight").value;
    height = document.getElementById("height").value;
    error = "Please enter some values";
    height /= 100;
    height *= height;
    bmi = weight/height;
    bmi = bmi.toFixed(1);

    if (bmi <= 18.4) {
        measure = "Your BMI is " + bmi + " which means " + "you are Underweight";
    } else if (bmi >= 18.5 && bmi <= 24.9) {
        measure = "Your BMI is " + bmi + " which means " + "You are Normal";
    } else if (bmi >= 25 && bmi <= 29.9) {
        measure = "Your BMI is " + bmi + " which means " + "You are Overweight";
    } else if (bmi >= 30) {
        measure = "Your BMI is " + bmi + " which means " + "You are Obese";
    }

    if (weight === 0 ) {
        document.getElementById("results").innerHTML = error;
    } else if (height === 0){
        document.getElementById("results").innerHTML = error;
    }
     else {

        document.getElementById("results").innerHTML = measure;
    }
    if (weight < 0) {
        document.getElementById("results").innerHTML = "Negative Values not Allowed";
    }
}

Upvotes: 1

Views: 917

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

To add the BMI data to the database, you do something like this:

weight = document.getElementById("weight").value;
height = document.getElementById("height").value;
error = "Please enter some values";
height /= 100;
height *= height;
bmi = weight/height;
bmi = bmi.toFixed(1);

firebaseRef.child("BMI").push({
  weight: weight,
  height: height,
  bmi: bmi
});

Aside from (obviously) passing in the values you got from the HTML, this code calls push(), which generates a new unique location in the JSON every time it's called. That way the values you enter won't overwrite what's already there.

Note that HTML elements typically return value as a string. So you might still have to convert the weight and height to numbers after getting from the HTML element:

weight = parseFloat(document.getElementById("weight").value);
height = parseFloat(document.getElementById("height").value);

Finally: saving data to Firebase is pretty well covered in the Firebase documentation and in the Firebase codelab for web developers. I highly recommend you check those out. A few hours spent there, saves many questions down the line.

Upvotes: 1

Related Questions