Brett Comardelle Brett Comardelle - 6 months ago 27
Javascript Question

Simplest way to add data to Firebase with Javascript

I've looked at previous posts and the documentation and other resources, but I just cannot fiugre out how to add an entry to my firebase database when a button is clicked. The button calls writeNewPost(). Here is what I tried

<button type="submit" class="btn btn-light" onclick="writeNewPost()">Submit</button>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script>

<script>
var config = {
apiKey: MYAPIKEY,
authDomain: MYDOMAIN,
databaseURL: MYURL,
projectId: MYPROJECT,
storageBucket: STORAGEBUCKET,
messagingSenderId: SENDERID
};
firebase.initializeApp(config);
</script>

<script>
function writeNewPost() {
var postData = {
"Name": "Brett"
};

var newPostKey = firebase.database().ref().push().key;

var updates = {};
updates['/' + newPostKey] = postData;

return firebase.database().ref().update(updates);
}
</script>


All I want is to have "Name":"Brett" under the root.

Answer Source

Your code seems quite good. To get you going with simple communication with Firebase you first need to set some rules https://firebase.google.com/docs/database/security/quickstart

P.S: used your code, added rules into Database → Rules(Tab) and it works.

Disclaimer!! use the below only for a limited test period of time - since it opens your database to the public - And read always the warnings that might appear in the panel!

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

From the docs:

It is essential that you configure these rules correctly before launching your app to ensure that your users can only access the data that they are supposed to.


The way you presented your code - the inline onclick= points to a function that is only defined later in your code - therefore you're at risk of it being undefined.

A better way to keep your JS in one place.
Remove the inline onclick and add an ID selector like id="submitPost"

<button id="submitPost" type="submit" class="btn btn-light">Submit</button>

Than inside your script use:

document.getElementById("submitPost").addEventListener("click", writeNewPost);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download