I've just tried To write a very basic data to my firebase database but it isn't working. Here's is the code that i've used
<script src="https://www.gstatic.com/firebasejs/9.8.4/firebase-database.js"></script>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.4/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
function writeUserData() {
firebase.database().ref('users').set({ uId: document.getElementById('fname').value,
refercode:document.getElementById('lname').value})
</script>
<form name="myForm">
<div class="col-25">
<label for="fname">text1</label>
</div>
<div class="col-75">
<input type="text" id="fname" name="firstname" placeholder="Your PlayStore Email.." required></input>
<div class="col-25">
<label for="lname">text2</label>
</div>
<div class="col-75">
<input type="text" id="lname" name="codename" placeholder="Your PlayStore Email.." required></input>
</div> <button onclick="writeUserData()" class="button">Request Withdrawal</button></form>
But this isn't writing any data on to my database. It returns an error in console, "writeUserData" is not defined.How can i solve this?
Since your script block is typed as a module, the internals of it are not available globally.
One way to make your writeUserData available to the button click handler is to add it to the window object as shown here: JS modules - ReferenceError: <function> is not defined
But a better solution is to not depend on an inline onclick handler, and instead attach the handler in the script module itself with addEventListener like:
<script type="module">
...
function writeUserData() {
firebase.database().ref('users').set({ uId:
document.getElementById('fname').value,
refercode:document.getElementById('lname').value
})
}
// ๐
document.querySelector('button').addEventListener('click', writeUserData)
</script>