getting started with firebase with javascript - javascript

I'm just getting started with firebase and javascript html to make a website for my app.
all I'm trying to do is access any value from firebase and print it on the website.
I followed firebase's quickstart tutorial and copied the exact same code they have: https://www.youtube.com/watch?v=k1D0_wFlXgo
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript</title>
</head>
<body>
<h1 id="bigOne"></h1>
<script src="https://www.gstatic.com/firebasejs/3.3.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyD0C9hhfpdKEIahisG0VNInZZGjCyf5Lo0",
authDomain: "game-of-chats-ce897.firebaseapp.com",
databaseURL: "https://game-of-chats-ce897.firebaseio.com",
storageBucket: "game-of-chats-ce897.appspot.com",
};
firebase.initializeApp(config);
var bigOne = document.getElementById('bigOne');
var dbRef = firebase.database().ref().child('text');
dbRef.on('value', snap => bigOne.innerText) = snap.val())
</script>
</body>
</html>
am I missing something? I am new so there might be one small step that I'm missing.

Try with:
dbRef.on('value', function(snapshot) {
bigOne.innerText = snapshot.val();
});

Related

Onload Function Not Triggering Function, no console errors

I am trying to make a JavaScript Announcement which includes a function main() in this case, that is not triggering upon onload function in the body tag I have inserted, , but when I manually trigger this function in Chrome's Console, it works as expected, please help me..
I have Also Used Firebase's Realtime Database for one of the values out of more values that I will use from there..
Code:
Here is the HTML & JS
or you can see the Code:
HTML:
// Firebase Setup
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyBz2pk-ec0yn7H25fzLaXI13CmAX4xp1-o",
authDomain: "learningdb-1.firebaseapp.com",
databaseURL: "https://learningdb-1-default-rtdb.firebaseio.com",
projectId: "learningdb-1",
storageBucket: "learningdb-1.appspot.com",
messagingSenderId: "287578856127",
appId: "1:287578856127:web:0894a806aa5b039bafc40a",
measurementId: "G-682XPG49J1"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Add .child('the reference of the value you want to see like dbRef.on')
var dbRef = firebase.database().ref();
let announcements;
var ann = firebase.database().ref().child('announcements');
ann.on('value', snap => announcements = snap.val());
// /Firebase Setup and Inialization Complete!
// announcements = true;
function main() {
if (announcements == true) {
mainAnnouncement = "AVMC has decided to recontinue the Minecraft Network services and is expected to be up by 20-25 March. This given date may be extended seeing the amount of potential problems in the Network as of being down for a good time. There will be tests done with some feature updates and more before going up! ";
announcementTitle = "Important Notice! ";
jsPara = document.getElementById('jsId');
jsPara2 = document.getElementById('jsPara')
jsPara.innerHTML += `Announcements is set to "${announcements}" <br>
<b> [ANNOUNCEMENT BODY] </b> <br>`;
jsPara2.innerHTML +=
`<div class="alert alert-warning" role="alert">
<h5>
<b>${announcementTitle}</b>
</h5>
<hr>
${mainAnnouncement}
</div>`
} else if (announcements == false) {
jsPara = document.getElementById('jsId');
jsPara.innerHTML = `Announcements is set to "${announcements}"`;
}
}
<!DOCTYPE html>
<html>
<head>
<title>LearningDB-1 | AVMC</title>
<script src="https://www.gstatic.com/firebasejs/8.3.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.0/firebase-database.js"></script>
<script src="js/index.js"></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body onload="main()">
<br>
<div class="container">
<h4><u><b>This code triggers an Announcement
when the value "announcement" is set to "true"</u></b></h4>
<h5 id="jsId"><b> [ANNOUNCEMENT] </b></h5>
<div id="jsPara"></div>
</body>
</script>
</html>

Unity WebGL form posts to Cloud Firestore with Firebase JS SDK

My goal is to build a WebGL game in Unity that has a specific form and upon submission that form posts data into one of the Firebase storage solutions. After reading this article, it's clear to me I need to use Cloud Firestore instead of Realtime Database. Good news is that as of of March 2020, one of the team members wrote,
we released Firebase Unity SDK 6.12.0 which includes an alpha release
of Firestore.
Thing is, Firebase's Unity SDK isn't for WebGL builds and, for someone going through that thought process, could use Firebase JS SDK (spam alert). From looking at the release notes, one can see that Firebase JS SDK supports Firestore and so this has all the conditions in place for a quick solution.
So, I've gone to Firebase console, created a project, a Web app to use Firebase JS SDK and this process gave as output the following code
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
with a message saying
Copy and paste these scripts into the bottom of your tag, but
before you use any Firebase services
In addition to that, this is how to Call JavaScript functions from Unity scripts and this is a Cloud Firestore JS Sample App.
Given this information, how can then the form be created?
Let's say you want a form that receives as input
String
Number
Text from the user
In your Firestore console, create a collection and give it a name (like formDataTree), give an autoID and add the fields
strVal
intVal
webVal
Then, I would put those scripts at the bottom of the head tag in your WebGL template. So, create a folder in Assets named WebGLTemplates, and a folder named New Template (or whatever name you will) and add an index.html there.
According to the documentation, this index.html should be similar to
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | %UNITY_WEB_NAME%</title>
<script src="%UNITY_WEBGL_LOADER_URL%"></script>
<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");
</script>
</head>
<body>
<div id="unityContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>
</body>
</html>
So, with this new information, it'll be something like this
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | %UNITY_WEB_NAME%</title>
<script src="%UNITY_WEBGL_LOADER_URL%"></script>
<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");
</script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
</head>
<body>
<div id="unityContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>
</body>
</html>
Then, under Player settings, select that template.
Then in the body of the template, have a form with its visibility to hidden. Include things from the game as well as any inputs you want filled out in the browser:
<form id="webForm" style="visibility:hidden;">
<input type="hidden" id="stringInput" name="stringInput">
<input type="hidden" id="intInput" name="intInput">
<label for="webInput">web input</label><input type="text" id="webInput" name="webInput">
<button type="submit">Submit</button>
</form>
Then below the Firebase script and the form, include a submit listener for the form on the page which will submit it to Firestore (based on this answer):
myForm.addEventListener('submit', function(evt) {
evt.preventDefault(); //Prevent the default form submit action
var strVal = myForm.stringInput.value;
var intVal = myForm.intInput.value;
var webVal = intInput.webInput.value;
var formData = {
"strVal" : strVal,
"intVal" : intVal,
"webVal" : webVal
};
firebase.database().ref('/formDataTree').push( formData ); // Adds the new form data to the list under formDataTree node
});
All in all, the index.html should be something like this
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Change Mapping | %UNITY_WEB_NAME%</title>
<script src="%UNITY_WEBGL_LOADER_URL%"></script>
<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");
</script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
</head>
<body>
<div style="height:20px; width: %UNITY_WIDTH%px; background: green;" onclick="unityInstance.SetFullscreen(1)"><b>Click here to make it full screen.</b></div>
<div id="unityContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>
<form id="webForm" style="visibility:hidden;">
<input type="hidden" id="stringInput" name="stringInput">
<input type="hidden" id="intInput" name="intInput">
<label for="webInput">web input</label><input type="text" id="webInput" name="webInput">
<button type="submit">Submit</button>
</form>
<script>
var myForm = document.getElementById("webForm");
myForm.addEventListener('submit', function(evt) {
evt.preventDefault(); //Prevent the default form submit action
var strVal = myForm.stringInput.value;
var intVal = myForm.intInput.value;
var webVal = intInput.webInput.value;
var formData = {
"strVal" : strVal,
"intVal" : intVal,
"webVal" : webVal
};
firebase.database().ref('/formDataTree').push( formData ); // Adds the new form data to the list under formDataTree node
});
</script>
</body>
</html>
Using the apiKey, authDomain, etc in the template it means that it will show up when inspecting the page or viewing page source as. Yet, as mentioned here, it's ok to share that information.
Then, in your Assets folder, create a Plugins folder and add to it a .jslib file, for instances named form.jslib, that has a function that shows the form, and puts game data into the form's hidden inputs.
mergeInto(LibraryManager.library, {
ShowWebForm: function (importantString, importantInt) {
var myForm = document.getElementById("webForm");
myForm.stringInput.value = Pointer_stringify(importantString);
myForm.intInput.value = importantInt;
myForm.style.visibility="visible"
},
});
After the steps up to this point, if you get in the console net::ERR_BLOCKED_BY_CLIENT, simply deactivate AdBlocker for that site as that's why you get that error.
Finally, in Unity, declare that function and call it when appropriate. So, considering you have a newly created scene (so it only has Main Camera and Directional Light), you could call that method in some code that gets called in the new scene. It's a static method so as long as you can find the data you need for the parameters you can call it from anywhere.
[DllImport("__Internal")]
private static extern void ShowWebForm(string importantString, int importantInt);
public void Start()
{
// Suppose we want to send the version of unity the app is running on
// and the unix timestamp at start
string unityVersion = Application.unityVersion;
System.DateTime epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0,
System.DateTimeKind.Utc);
int cur_time = (int)(System.DateTime.UtcNow - epochStart).TotalSeconds;
ShowWebForm(unityVersion, cur_time);
}
Alternatively, if you don't want to have the user fill things out in the browser, you can leave the form invisible and instead of setting it to visible, dispatch a submit event:
mergeInto(LibraryManager.library, {
ShowWebForm: function (importantString, importantInt) {
var myForm = document.getElementById("webForm");
myForm.stringInput.value = Pointer_stringify(importantString);
myForm.intInput.value = importantInt;
myForm.webInput.value = "some other value from the game could go here";
myForm.dispatchEvent(new Event('submit'));
},
});
Can't test at the moment, so be aware of typos or other syntax errors.

Firebase not defined js error when trying to display real-time firebase db data on webpage

I am using a moisture sensor for my first IoT project. I am saving the data from the sensor in a real-time Firebase database. For my webpage I am using glitch.com, and I am trying to display the data from the db on my webpage. I tried coding this myself, but got pretty much nowhere. So I decided to remix an existing glitch.com "Firebase Read" project. However I am encountering a problem, it's saying: 'firebase' not defined in the following 3 lines (In the first line listed below, it's also saying config is not defined):
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
var myDBConn = firebase.database().ref("Moisture");
I currently have the following in my js file:
<script src="https://www.gstatic.com/firebasejs/7.11.0/firebase.js"></script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
// Initialize Firebase
var firebaseConfig = {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
// List to hold my moisture value
var myMoisture = [];
// Define database connection to correct branch, Moisture
var myDBConn = firebase.database().ref("Moisture");
// Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
myDBConn.on("child_added", function(data, prevChildKey){
// The data returned from the branch is put into a variable, dataPoint
var dataPoint = data.val();
// Convert the 'Temp' field from dataPoint into integers, then put them into the myTemps list
myMoisture.push(parseInt(dataPoint.Temp));
// Add all the Temps and get the total
var totalT = 0;
var i=0;
for (i=0; i<myMoisture.length; i++){
totalT += myMoisture[i];
}
// Create an average by dividing the sum of temps by the number of temps
var average = totalT / myMoisture.length;
// Update the page elements with the average and the last item (most recent) off the list
document.getElementById("averageT").innerHTML=average;
document.getElementById("LiveT").innerHTML=myMoisture[myMoisture.length - 1];
});
This in my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello!</title>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.11.0/firebase.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Reading from Firebase Cloud Database</h1>
Live Moisture Reading: <a id="LiveT">---</a> <br>
Average Temperature: <a id="averageT">---</a>
</body>
</html>
And this is shown by the debugger (I don't know if this information is relevant and what it means, but maybe it's useful):
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (net.js:1270:14)
at listenInCluster (net.js:1318:12)
at Server.listen (net.js:1405:7)
at Lws.listen (/opt/nvm/versions/node/v10.15.3/pnpm-global/1/node_modules/.registry.npmjs.org/lws/1.3.2/node_modules/lws/index.js:81:12)
at WsServe.execute (/opt/nvm/versions/node/v10.15.3/pnpm-global/1/node_modules/.registry.npmjs.org/lws/1.3.2/node_modules/lws/lib/command/serve.js:296:26)
at WsServe.execute (/opt/nvm/versions/node/v10.15.3/pnpm-global/1/node_modules/.registry.npmjs.org/local-web-server/2.6.0/node_modules/local-web-server/lib/command/serve.js:11:18)
at Map.start (/opt/nvm/versions/node/v10.15.3/pnpm-global/1/node_modules/.registry.npmjs.org/cli-commands/0.4.0/node_modules/cli-commands/index.js:26:18)
at WsCliApp.start (/opt/nvm/versions/node/v10.15.3/pnpm-global/1/node_modules/.registry.npmjs.org/lws/1.3.2/node_modules/lws/lib/cli-app.js:9:26)
at Function.run (/opt/nvm/versions/node/v10.15.3/pnpm-global/1/node_modules/.registry.npmjs.org/lws/1.3.2/node_modules/lws/lib/cli-app.js:15:29)
at Object.<anonymous> (/opt/nvm/versions/node/v10.15.3/pnpm-global/1/node_modules/.registry.npmjs.org/local-web-server/2.6.0/node_modules/local-web-server/bin/cli.js:5:29)
What things could I try next?
Quick scan of the FireBase docs
I see that your FireBase import is slightly wrong:
Try changing it to:
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.11.0/firebase-app.js"></script>
The docs are here: https://firebase.google.com/docs/web/setup

How do I update a single value displayed on my website with JS?

With the help of a realtime firebase database and some arduino code, I am displaying Moisture levels of potting soil on my website. However when the firebase data is updated (every 0.3 seconds), instead of also updating the single value on the website, it adds a new line/print every update. After a short while, my website now looks like this:
Moisture: 661Moisture: 658Moisture: 660Moisture: 658Moisture: 657, and it keeps on adding the Moisture: xxx after it with every update. What I want to happen is to just have it displayed once, and push the data so it updates the first value, rather than adding a new one.
I'll leave my code below, how can I go about doing this? It's hard to find things about this on the internet as I am not sure what I am looking for (new to JS).
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
};
firebase.initializeApp(config);
</script>
<script>
var database = firebase.database();
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "plant-patrol"
var childKey = snapshot.child().key; // "Moisture"
});
</script>
<script>
var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
console.log(snapshot.val());
var snapshotJSON = JSON.stringify(snapshot.val());
var moisture = snapshotJSON;
moisture = moisture.replace(/[{""}]/g, '');
moisture = moisture.replace(/[:]/g, ': ');
document.write(moisture);
}, function (error) {
console.log("Error: " + error.code);
});
</script>
<script src="/script.js" defer></script>
</head>
</html>
var div = document.getElementById('moisture');
div.innerHTML = 'Moisture: 55%';
<div id='moisture'></div>
Your are using document.write(moisture). This writes the moisture variable on the document each time is received.
What you want is to replace a specific text in the document. To do that you must create an element with an unique ID like:
<div id='moisture'></div>
First, assing that element to a variable:
var moistureDiv = document.getElementById('moisture');
Then, remove the document.write(moisture) and add this code to replace the text on the element with "moisture" ID:
moistureDiv.innerHTML = moisture;

Troubles pushing data to Firebase with a text input field jQuery

I am just learning FireBase and have been stuck on this problem for awhile. I am wanting the user to enter a string into the input field press submit, and that data will be sent to FireBase. Any kind of help would be awesome!
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js">
</script>
<script>
var config = {
apiKey: "AIzaSyCBUbK2d_H7QF3J8BDBPHAHSGJAGS",
authDomain: "my-project.firebaseapp.com",
databaseURL: "https://my-project.firebaseio.com",
projectId: "my-project",
storageBucket: "my-project.appspot.com",
messagingSenderId: "845405833425"
};
firebase.initializeApp(config);
var database;
database = firebase.database();
var ingInput;
ingInput = $("#fridge");
var submit = $("#submit");
submit.click(sendIng);
//Sends to firebase
function sendIng(){
//Makes the object
var data = {
ingredients: ingInput.text()
}
console.log(data);
var ref = database.ref("ingredients");
var ingredients = ing.push(data);
}
</script>
</head>
<div id="ingredients-submit">
<label>Store this item:</label>
<input type="text" id="fridge">
<button id="submit">Store</button></div>

Categories