I'm working on the front end for a project to display a graph of data collected from sensors. I'm following Net Ninja's youtube series on connecting to firebase, as well as trying many other approaches found online, but nothing I try works. I cannot get data from my firebase test database to display, and also can't display example data from others. I was hoping for a bit of help in what I could have missed.
const dataList = document.querySelector('#data-list');
// create element & render data
function renderData(doc) {
let li = document.createElement('li');
let time = document.createElement('span');
let data = document.createElement('span');
li.setAttribute('data-id', doc.id);
time.textContent = doc.data().time;
data.textContent = doc.data().data;
li.appendChild(time);
li.appendChild(data);
dataList.appendChild(li);
}
// getting data
db.collection('sensorData').get().then(snapshot => {
snapshot.docs.forEach(doc => {
renderData(doc);
});
});
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-database.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>test</h1>
<div class="content">
<form id="add-data-form"></form>
<ul id="data-list"></ul>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.9.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.9.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-database.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = { **
FIREBASE DATA **
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
firebase.analytics();
</script>
<script src="app.js"></script>
</body>
</html>
When I launch the index, I only see the "test" heading, no data from the firebase. I have used powershell to initialise the database, that didn't make a difference though. Any help would be greatly appreciated, thank you
Related
Hi I am working with IOTA distributed ledger. I have iota client library for node.js.
I want to read data from node.js file where I access IOTA distributed ledgers and pass it to Html where user can see.
My client.js file:
const Iota = require('#iota/core');
const Extract = require('#iota/extract-json');
const iota = Iota.composeAPI({
provider: 'https://nodes.devnet.iota.org:443'
});
let x = [];
iota.getBundlesFromAddresses(['PXMPEGYZCOVEOSRAUXY9VYRBHJBSDWORWQNBDJRVEFTMXZWLTQZSPHEUDMXT9YKGPMMSVDSNHSJNWQUOX'])
.then(bundle => {
for (let i = 0; i < bundle.length; i++) {
console.log(JSON.parse(Extract.extractJson(bundle[i])).message);
x[i]=JSON.parse(Extract.extractJson(bundle[i])).message;
}
})
.catch(err => {
console.error(err);
});
I want to pass x[i] variable to html.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="client">
{{ x[0]}}
{{ x[1]}}
{{ x[2]}}
</div>
<script src="myApp.js"></script>
<script src="client.js"></script>
</body>
</html>
I know how to read data from controller but how am I gonna read data if client.js has imported libraries.
I tried in Angular to convert libraries to typescript but couldnt figure out.
This is typically done in package.json, such as server or build
I am trying to call firebase functions from client side but I'm getting error that firebase.functions is not a function
main.js:18 Uncaught TypeError: firebase.functions is not a function
here is main.html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body >
<div class="jumbotron text-center">
<h1>My First Bootstrap Page</h1>
<p>Resize this responsive page to see the effect!</p>
</div>
<script src="https://www.gstatic.com/firebasejs/8.0.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.0.2/firebase-functions.js"></script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.0.2/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/8.0.2/firebase-analytics.js"></script>
<script type="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>
<script type="text/javascript">
var firebaseConfig = {
apiKey: "41414414I",
authDomain: "414444.firebaseapp.com",
databaseURL: "https://414144.firebaseio.com",
projectId: "414-c4cc",
storageBucket: "4144-cc4cc.appspot.com",
messagingSenderId: "414542",
appId: "1:41:web:31415425",
measurementId: "G-542g542"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
// Initialize Cloud Functions through Firebase
var functions = firebase.functions();
</script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
</script>
<script src="main.js"></script>
</body>
</html>
here is my main.js file
random()
function random(){
var randomNumber = firebase.functions().httpsCallable('randomNumber');
randomNumber({text: messageText}).then(function(result) {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
console.log(sanitizedMessage)
}).catch(function(error) {
// Getting the Error details.
var code = error.code;
var message = error.message;
var details = error.details;
console.log(message)
// ...
})
}
how can I fix the error and call firebase function from the client side?
After implementing Doug's answer it displayed
Uncaught ReferenceError: require is not defined
Your Firebase script includes are incorrect and out of order:
<script src="https://www.gstatic.com/firebasejs/8.0.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.0.2/firebase-functions.js"></script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.0.2/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/8.0.2/firebase-analytics.js"></script>
Please review the instructions in the documentation. Firstly, don't include firebase.js. Secondly, put them in the correct order, with firebase-app listed first.
<script src="https://www.gstatic.com/firebasejs/8.0.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.0.2/firebase-functions.js"</script>
<script src="https://www.gstatic.com/firebasejs/8.0.2/firebase-analytics.js"</script>
I'm trying to retrieve data from firebase db using Html and js I'm not very good on web dev so this is my first web dev not quite familiar with it, so my users stored by there uid here's the data struct
her is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Side Navigation Bar</title>
<link rel="stylesheet" href="sidebarStyle.css">
<script src="https://kit.fontawesome.com/b99e675b6e.js"></script>
</head>
<body>
<div class="wrapper">
<table>
<tr>
<th>name:</th>
<th>phone:</th>
<th>id:</th>
</tr>
<tbody id="table">
</tbody>
</table>
</div>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-database.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIza........",
authDomain: "........",
databaseURL: ".........",
projectId: ".......",
storageBucket: "........",
messagingSenderId: ".......",
appId: "1:.....:web:.......",
measurementId: "G-......"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script src="usersTable.js"></script>
</body>
</html>
my Javascript code is in a separate file -> usersTable.js another problem is when I'm writing firebase no auto-completion appears I did install typescript, the code that I tried is following this guy instruction but didn't work for me https://www.youtube.com/watch?v=nUUPedePJ4o
if there is anything wrong with my code or I do have to install firebase tools or not let me know
To retrieve data of signed-in user:
[Assuming that you want the details of the signed-in user]
// get current logged in user details
const user = firebase.auth().currentUser;
// get the branch of the user
const userBranch = firebase.database().ref('/users/'+user.uid);
// retrieve the data from that branch - Remember this is an asynchronous function - it returns promise
userBranch.once('value').then((snapShot)=>{
var userPhoneNo = snapShot.val().phone;
var userPic = snapShot.val().profileImageUrl;
var userName = snapShot.val().username;
});
Resource: Link
If you want to learn more about asynchronous functions - Link
About your second problem, there are no extensions available for autocomplete in JavaScript for Firebase.
Edit 1:
[Fetching all the users from users branch]
// this will get the whole user branch
const userBranch = firebase.database().ref('/users');
// retrieve the data from the database
userBranch.once('value').then((snapShot)=>{
var userDetaills = snapShot.val()
userDetails.forEach((user)=>{
let userPhone = user.phone;
let userPic = user.profileImageUrl;
let userName = user.username;
// your rest of the logic
});
});
I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.
You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.
Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
I've been working on a web application, built by using CakePHP 3, that stores lines of text in Firebase's realtime database. It starts pushing the data to the database as soon as a request is received at one of the end points of the controller. In the meantime I'd like to see those lines of text to be displayed on the page one by one.
So far, I've made it possible to deal with the request process and now I can send the data to my web page. I could follow the text being sent both from console on the browser and html outputs. However, I'm stuck with installing AngularJS on the front end, so any help on this very topic will be appreciated.
As the things stands now, since I couldn't built AngularJS, I cannot see any changes on my page when I use the line below:
document.getElementById("demo").innerHTML = data.val();
Since there are many documentations, mostly outdated, on the web, I'm having quite hard time finding the useful information that I can use. I'd really appreciate any help on this.
src/Template/Visits/code.ctp :
<!DOCTYPE html>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.0.3/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script>
<html lang="en">
<body>
<p id="demo"></p>
<script>
// Initialize Firebase
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
storageBucket: "...",
};
firebase.initializeApp(config);
var codeRef = firebase.database().ref('code/');
codeRef.on('child_added', function(data) {
console.log(data.val());
//document.getElementById("demo").innerHTML = data.val();
//document.getElementById("demo").innerHTML = "<br>";
// document.write(data.val());
// document.write("<br>");
window.scrollBy(0,50); // scroll to make sure bottom is always visible
});
</script>
</body>
src/Template/Layout/code.ctp :
<!DOCTYPE html>
<html lang="en">
<?php echo $this->Html->css('style'); ?>
<head>
<br>"Push the button!"</br>
</head>
<body>
<!-- Page Content -->
<div id="content" class="container">
<?= $this->Flash->render() ?>
<div class="row">
<?= $this->fetch('content') ?>
</div>
</div>
</body>
</html>
Well, I managed to come up with a solution but I'm sure that there are many other solutions out there. It was needed to declare the application, which was obviously missing before.
src/Template/Visits/code.ctp :
<!DOCTYPE html>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.0.3/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script>
<html lang="en">
<body>
<p id="demo">Push the button...</p>
<div ng-app="MyModule" ng-controller="MyController"></div>
<script>
//------- Initialize Firebase ---------------
var config = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DB_URL",
storageBucket: "YOUR_STORAGE_BUCKET",
};
firebase.initializeApp(config);
var codeRef = firebase.database().ref('code/');
//------- Application Module ----------------
var app = angular.module('MyModule', []);
document.getElementById("demo").innerHTML = "";
app.controller("MyController", ["$scope", function($scope) {
codeRef.on('child_added', function(data) {
console.log(data.val());
document.getElementById("demo").innerHTML += data.val();
document.getElementById("demo").innerHTML += "<br>";
window.scrollBy(0,50); // scroll to make sure bottom is always visible
});
}]);
</script>
</body>
</html>