Firebase says initializeApp is not defined after adding libraries - javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>List</title>
</head>
<body>
<table>
<thead>
<th>Name</th>
<th>Email</th>
<th>Message</th>
</thead>
<tbody id="tbody1">
</tbody>
</table>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-database.js"></script>
<script id="MainScript">
//-----------Config------------//
var firebaseConfig = {
apiKey: "----------------------",
authDomain: "-firebaseapp.com",
databaseURL: -.firebaseio.com",
projectId: "-9677d",
storageBucket: "--.appspot.com",
messagingSenderId: "-------3",
appId: "------------------------"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//----------Getting-The-Data-------------------//
function SelectAllData() {
firebase.database().ref('People').on('value',
function(AllRecords){
AllRecords.forEach(
function(CurrentRecord){
var name = CurrentRecord.val().Name;
var email = CurrentRecord.val().Email;
var message = CurrentRecord.val().Message;
AddItemsToTable(name,email,message);
}
);
});
}
window.onload = SelectAllData;
//----------Filling-The-Table-----------------//
var stdNo = 0;
var tbody = document.getElementById('tbody1');
function AddItemsToTable(Name,Email,Message) {
var trow = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
td1.innerHTML= sdtNo;
td1.innerHTML= Name;
td1.innerHTML= Email;
td4.innerHTML= Message;
trow.appendChild(td1);
trow.appendChild(td2);
trow.appendChild(td3);
tbody.appendChild(trow);
}
function AddAllItemsToTable(Name){
stdNo=0;
tbody.innerHTML="";
Name.forEach(element => {
AddItemToTable(element.Name, element.Email, element.Message)
});
}
</script>
</body>
This is my code. Above I censored my firebase config. Whenever I run this, it says stdNo is not defined. I am trying to display data from my firebase database into a table. My firebase database looks like this! My Firebase Database Setup
I have tried countless tutorials but none are helping. I always get this error.
Uncaught ReferenceError: sdtNo is not defined
at AddItemsToTable (LIST.php:65:20)
at LIST.php:50:11
at DataSnapshot.ts:148:14
at ke.inorderTraversal (SortedMap.ts:229:9)
at We.inorderTraversal (SortedMap.ts:755:23)
at Je.forEachChild (ChildrenNode.ts:350:29)
at cn.forEach (DataSnapshot.ts:147:27)
at LIST.php:45:18
at EventRegistration.ts:133:12
at Nt (util.ts:588:5)

Related

Javascript array not displayed in HTML table

I am trying to loop through arrays of data which then displayed in the html table. I am able to create a new object and pass the data in the object to an empty array. However, the problem that I am facing right now is that the arrays data is not showing in the table. At the same time, there are no errors shown in the console. I checked all info in the function addToHTML() and it supposed to be correct.I have no idea what I did wrong ? The following are the javascript and html code :
// Main Book object model
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
// Library object model
function Library() {
this.myLibrary = [];
this.addToLibrary = function(myLibrary) {
this.myLibrary.push(myLibrary);
}
}
// Create new book object
let book1 = new Book('Awaken the Giant Within', 'Tony Robbins', '351', 'already read');
let book2 = new Book('Think and Grow Rich', 'Napoleon Hill', '271', 'currently reading');
let book3 = new Book('Rich Dad Poor Dad', 'Robert T. Kiyosaki', '289', 'finish read');
// Create new library object
let library = new Library();
// Add books to the empty array
library.addToLibrary(book1);
library.addToLibrary(book2);
library.addToLibrary(book3);
// Function to add main Book to HTML content
function addToHTML() {
for (let i=0; i < library.myLibrary.length ; i++ ) {
let dataContainer = document.querySelector('#dataContainer');
let titleColumn = document.getElementById('title');
let authorColumn = document.getElementById('author');
let pagesColumn = document.getElementById('pages');
let readColumn = document.getElementById('read');
let book_title = library.myLibrary[i].titleColumn;
let book_author = library.myLibrary[i].authorColumn;
let book_pages = library.myLibrary[i].pagesColumn;
let book_read = library.myLibrary[i].readColumn;
titleColumn.textContent = book_title;
authorColumn.textContent = book_author;
pagesColumn.textContent = book_pages;
readColumn.textContent = book_read;
dataContainer.appendChild(titleColumn);
dataContainer.appendChild(authorColumn);
dataContainer.appendChild(pagesColumn);
dataContainer.appendChild(readColumn);
}
}
console.log(library.myLibrary);
addToHTML();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Book Object</title>
</head>
<body>
<h1>Book template</h1>
<form>
<table id="book-table">
<thead>
<tr>
<th> Title </th>
<th> Author </th>
<th> Pages </th>
<th> Read </th>
</tr>
</thead>
<tbody>
<tr id="dataContainer">
<td id="title"></td>
<td id="author"></td>
<td id="pages"></td>
<td id="read"></td>
</tr>
</tbody>
</table>
</form>
<script src="script.js"></script>
</body>
</html>
Needed to change the HTML + js code
// Main Book object model
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
// Library object model
function Library() {
this.myLibrary = [];
this.addToLibrary = function(myLibrary) {
this.myLibrary.push(myLibrary);
}
}
// Create new book object
let book1 = new Book('Awaken the Giant Within', 'Tony Robbins', '351', 'already read');
let book2 = new Book('Think and Grow Rich', 'Napoleon Hill', '271', 'currently reading');
let book3 = new Book('Rich Dad Poor Dad', 'Robert T. Kiyosaki', '289', 'finish read');
// Create new library object
let library = new Library();
// Add books to the empty array
library.addToLibrary(book1);
library.addToLibrary(book2);
library.addToLibrary(book3);
// Function to add main Book to HTML content
function addToHTML() {
for (let i=0; i < library.myLibrary.length ; i++ ) {
console.log(library.myLibrary)
let tbody = document.querySelector('#tbdy');
let content = `
<tr>
<td id="title">${library.myLibrary[i].title}</td>
<td id="author">${library.myLibrary[i].author}</td>
<td id="pages">${library.myLibrary[i].pages}</td>
<td id="read">${library.myLibrary[i].read}</td>
</tr>`
tbody.innerHTML += content;
}
}
console.log(library.myLibrary);
addToHTML();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Book Object</title>
</head>
<body>
<h1>Book template</h1>
<form>
<table id="book-table">
<thead>
<tr>
<th> Title </th>
<th> Author </th>
<th> Pages </th>
<th> Read </th>
</tr>
</thead>
<tbody id="tbdy">
<tr id="dataContainer">
<td id="title"></td>
<td id="author"></td>
<td id="pages"></td>
<td id="read"></td>
</tr>
</tbody>
</table>
</form>
<script src="script.js"></script>
</body>
</html>

HTML page is not displaying all records but overwriting previous results

I have two child records under Sensor, but its only displaying the last one, since it overwrites the previous record. How can I display the two results under each other or side by side?
This section in code is the one pulling records from Firebase realtime database.
get(child(dbref, "Sensor"))
.then((snapshot)=>{
snapshot.forEach((child)=>{
id_PumpID.innerHTML = "Pump ID: " + child.val().PumpID
id_StartTime.innerHTML = "StartTime: " + child.val().StartTime;
id_Cycle.innerHTML = "Cycle: " + child.val().Cycle;
id_Duration.innerHTML = "Duration: " + child.val().Duration;
id_GalsPumped.innerHTML ="GalsPumped: " + child.val().GalsPumped;
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="pump">
<br><br>
<h3 id="id_Cycle" type="number"></h3>
<h3 id="id_Duration" type="number"></h3>
<h3 id="id_GalsPumped" type="number"></h3>
<h3 id="id_PumpID" type="number"></h3>
<h3 id="id_StartTime" type="text"></h3>
<br><br>
</div>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
//config firebase
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxx-qE4zUGw",
authDomain: "pump-a559c.firebaseapp.com",
databaseURL: "https://pump-a559c-default-rtdb.firebaseio.com",
projectId: "pump-a559c",
storageBucket: "pump-a559c.appspot.com",
messagingSenderId: "838180391277",
appId: "1:838180391277:web:df22c7d634310ae135b264",
measurementId: "G-K66Z05LFCD"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
import {getDatabase, set, get, update, remove, ref, child}
from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js";
const db = getDatabase();
const dbref = ref(db);
get(child(dbref, "Sensor"))
.then((snapshot)=>{
snapshot.forEach((child)=>{
id_PumpID.innerHTML = "Pump ID: " + child.val().PumpID
id_StartTime.innerHTML = "StartTime: " + child.val().StartTime;
id_Cycle.innerHTML = "Cycle: " + child.val().Cycle;
id_Duration.innerHTML = "Duration: " + child.val().Duration;
id_GalsPumped.innerHTML ="GalsPumped: " + child.val().GalsPumped;
})
});
window.onload();
</script>
</body>
</html>
I solved the issue with switch - case statements. Please see the full code below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="refresh" content="5">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drainage Pump Monitor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
overflow:hidden;padding:13px 14px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
font-weight:normal;overflow:hidden;padding:13px 14px;word-break:normal;}
.tg .tg-l183{background-color:#96fffb;border-color:inherit;font-family:"Courier New", Courier, monospace !important;font-size:16px;
font-weight:bold;text-align:left;vertical-align:top}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
</style>
<header>
<h1>DRAINAGE PLAN</h1>
<h2>7310 S Cypresshead dr, Parkland FL 33067</h2>
</header>
<main>
<h2>Pump Monitor</h2>
<table id="pump_table" style="margin-top:130px; margin-left:10px;" class="tg" align="right">
<thead>
<tr>
<th class="tg-l183">PUMP</th>
<th class="tg-l183">START-TIME</th>
<th class="tg-l183">DURATION(mins)</th>
<th class="tg-l183">PUMPED(gals)</th>
<th class="tg-l183">CYCLE</th>
<th class="tg-l183">STATUS</th>
</tr>
</thead>
</table>
</main>
<footer>
<p>Copyright © <script>document.write(new Date().getFullYear());</script>, Innovative-Appliances. LLC </p>
</footer>
<script type="module">
// Import firebase app
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
// Configure Firebase
const firebaseConfig = {
apiKey: "Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxxxxxxxx-default-rtdb.firebaseio.com",
projectId: "pump-a559c",
storageBucket: "pump-a559c.appspot.com",
messagingSenderId: "838180391277",
appId: "1:838180391277:web:df22c7d634310ae135b264",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Import the Firebase database
import {getDatabase, set, get, update, remove, ref, child}
from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js";
const db = getDatabase();
const dbref = ref(db);
const heartBeat = Math.round(Date.now() / 1000);
get(child(dbref, "Sensor"))
.then((snapshot) => {
snapshot.forEach((child) => {
var bg_color = '#00FF00';
console.log(child.val().Heartbeat);
console.log("html heartbeat" + heartBeat);
// Check the heartbeat and report power failure if not found
if(child.val().Heartbeat < (heartBeat - 15))
{
console.log("no heart beat detected");
let table = document.querySelector('table');
let template = `
<tr>
<td bgcolor='red'>${"pump" + child.val().PumpID}</td>
<td bgcolor='red'>CONTROLLER FAILURE</td>
</tr>`;
table.innerHTML += template;
} else {
switch (child.val().Status) {
case "OFF":
// Set the color of row to red if no water flow is detected.
bg_color = 'yellow';
let table = document.querySelector('table');
let template = `
<tr>
<td bgcolor="${bg_color}">${"pump"+child.val().PumpID}</td>
<td bgcolor="${bg_color}">${child.val().StartTime}</td>
<td bgcolor="${bg_color}">${child.val().Duration}</td>
<td bgcolor="${bg_color}">${child.val().GalsPumped}</td>
<td bgcolor="${bg_color}">${child.val().Cycle}</td>
<td bgcolor="${bg_color}">${child.val().Status}</td>
</tr>`;
table.innerHTML += template;
break;
case "ON":
// Set the color of row to green
// if water flow is detected.
bg_color = '#00FF00';
let table2 = document.querySelector('table');
let template2 = `
<tr>
<td bgcolor="${bg_color}">${"pump"+child.val().PumpID}</td>
<td bgcolor="${bg_color}">${child.val().StartTime}</td>
<td bgcolor="${bg_color}">${child.val().Duration}</td>
<td bgcolor="${bg_color}">${child.val().GalsPumped}</td>
<td bgcolor="${bg_color}">${child.val().Cycle}</td>
<td bgcolor="${bg_color}">${child.val().Status}</td>
</tr>`;
table2.innerHTML += template2;
break;
case "FAIL":
// Set the color of row to red
// if pump failure is detected.
bg_color = 'red';
let table3 = document.querySelector('table');
let template3 = `
<tr>
<td bgcolor='red'>${"pump" + child.val().PumpID}</td>
<td bgcolor='red'>PUMP FAILURE</td>
</tr>`;
table3.innerHTML += template3;
break;
} // End of switch
} // End of else
})
});
</script>
</body>
</html>

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>

getting started with firebase with 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();
});

Categories