Using AngularJS to retrieve data from Firebase in CakePHP 3 - javascript

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>

Related

Javascript: calling firebase function from client side is not working

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>

how to retrieve users data from firebase stored by there uid

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
});
});

Can't get firebase to connect to HTML page

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

Firebase database returns null; upon refresh, it returns correct value

I've searched the existing discussions to no avail, so I thought I'd ask the community for assistance: I'm using JavaScript to fetch data from a Firebase database. The initial fetch works well; however, when I add a child to the database, my JavaScript webpage receives the new child data initially as "null". The strange thing is that if I refresh the webpage, the "null" is replaced by the correct data.
Here's my source for the webpage:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reading Firebase Database</title>
<script type="text/javascript" src="../d3.js"></script>
<style type="text/css">
/* No style rules here yet */
</style>
</head>
<body>
<div id="div1">
</div>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: confidential,
authDomain: confidential,
databaseURL: confidential,
projectId: confidential,
storageBucket: confidential,
messagingSenderId: "confidential"
};
firebase.initializeApp(config);
// Read Firebase Data
var database = firebase.database().ref().child("session");
database.on("child_added", snap => {
var dur = snap.child("dur").val();
var lat = snap.child("lat").val();
var lon = snap.child("lon").val();
// Display Firebase Data
var para = document.createElement("p");
var node = document.createTextNode(lon);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
});
</script>
</body>
</html>
And here is the Firebase outline:
Thank you, in advance, for your help. I really appreciate it.
You have to use on('value') function to get the value of each child . So whenever a new child is added on('value') will run for each child in firebase.
var database = firebase.database().ref().child("session");
database.on("value", snap => {
snap.forEach(snapshot => {
if ChildKey == newKey {
console.log(snapshot.val())
}
})
});

angularjs cookies with latest versions 1.4.1

Hello i want to store one sample cookie in my browser and read it.this not working for me
this is sample html code :
<!DOCTYPE html>
<html ng-app="KendoDemos">
<head>
<script src="/home/user/Desktop/kendo/angular.min.js"></script>
<script src="/home/user/Desktop/kendo/angular-cookies.min.js"></script>
<script src="/home/user/Desktop/kendo/app.js"></script>
</head>
<!-- Body tag augmented with ngController directive -->
<body ng-controller="MyCtrl">
<h1>Hello</h1>
</body>
</html>
and this my app.js file :
var app = angular.module("KendoDemos", ["ngCookies"]);
app.controller("MyCtrl",['$scope','$cookies','$cookieStore',MyCtrl]);
function MyCtrl($scope,$cookies,$cookieStore){
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
console.log(favoriteCookie);
}
Please help me.
I think you don't have a problem is really logical that your cookie myFavorite isn't set before putting it so you have to switch the instruction of setting and getting.
var app = angular.module("KendoDemos", ["ngCookies"]);
app.controller("MyCtrl",['$scope','$cookies','$cookieStore',MyCtrl]);
function MyCtrl($scope,$cookies,$cookieStore){
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
var favoriteCookie = $cookies.get('myFavorite');
console.log(favoriteCookie);
}

Categories

Resources