I'm trying to get some images from Firebase storage using Javascript in an HTML table, but I keep getting this error:
storage.refFromURL is not a function
Which is weird, considering the information from here
// Create a reference from a Google Cloud Storage URI
var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg')
The javascript code gets data from a Firebase database as well, and each child in the database contains an URL (defined in the db as imageUrl) to a Firebase storage in the form of gs://xxxxxxx, which I would like to use in a table. In other words, I would like to have the text from a database, and the image from storage, but I keep getting the "not a function" error. I have the following code:
index.js
var rootRef = firebase.database().ref().child("Test");
var storage = firebase.storage().ref();
rootRef.on("child_added", snap => {
var headline = snap.child("headline").val();
var url_ul = snap.child("imageUrl").val();
var storageRef = storage.refFromURL('url_ul').getDownloadURL().then(function(url) {
var test = url;
alert(url);
document.querySelector('img').src = test;
}).catch(function(error) {});
$("#table_body").append("</td><td>" + headline + "</td><td><img src='test' alt='' border=3 height=100 width=100></td>");
});
And the HTML file which contains the Firebase information:
<!DOCTYPE html>
<html>
<head>
<title>Firebase Web Basics</title>
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400,500,700" rel="stylesheet">
<script src="https://use.fontawesome.com/939e9dd52c.js"></script>
</head>
<body>
<div class="mainDiv" align="left">
<h1>All users</h1>
<table>
<thead>
<tr>
<td>Headline</td>
<td>Image</td>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
</div>
<script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxxxxxxx.firebaseio.com",
projectId: "xxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxx.appspot.com",
messagingSenderId: "0000000000000000"
};
firebase.initializeApp(config);
</script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="index.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-database.js"></script>
</body>
</html>
You essentially do:
var storage = firebase.storage().ref();
Which gives you a Reference.
Then you call:
storage.refFromURL('url_ul')
But refFromURL is only defined on the root Storage object.
So you'll want:
var storage = firebase.storage();
storage.refFromURL('url_ul')
Related
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 am trying to retrieve user Image and name from cloud firestore database to website. The image and name retrieval work good and the user image and name is appearing on the website screen. But the problem is that it is only fetching only Singal document which contain user Image and name . I have more document uploaded in the cloud firestore database which also contain different user Image and name. Pls see the Picture linked below.
Q1: How to fetch all the document which contain user Image and name
Q2: Why it is fetching only singal document?
Js code:
const list_div= document.querySelector('#list_div');
db.collection('student entry').get().then(function(querySnapshot){
querySnapshot.forEach(function(doc){
list_div.innerHTML="<div class='col-sm-4 mt-2 mb-1'>"+
"<div class='card'>"+
"<img src='"+doc.data().image+"' style='height:250px;'>"+
"<div class='card-body'><p class='card-text'>"+doc.data().fname+"</p></div></div>"
});
});
Html code:
<html>
<head>
<title>Blogs</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="main-list" id="list_div">
<div class="list-item">
</div>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first...make sure you remove -app from below line -->
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: " ",
authDomain: " ",
databaseURL: " ",
projectId: " ",
storageBucket: " ",
messagingSenderId: " ",
appId: " ",
measurementId: " "
};
firebase.initializeApp(config);
var db = firebase.firestore();
db.settings({ timestampsInSnapshots: true });
</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="defualt.js"></script>
</body>
</html>
You're reading and processing all documents from the collection. The only problem is that you're constantly setting the inner HTML of list_div instead of adding to it.
So the solution is to append the new element to the existing contents of list_div:
const list_div= document.querySelector('#list_div');
db.collection('student entry').get().then(function(querySnapshot){
list_div.innerHTML = "";
querySnapshot.forEach(function(doc){
list_div.innerHTML += "<div class='col-sm-4 mt-2 mb-1'>"+
"<div class='card'>"+
"<img src='"+doc.data().image+"' style='height:250px;'>"+
"<div class='card-body'><p class='card-text'>"+doc.data().fname+"</p></div></div>"
});
});
Aside from some formatting the big change is the addition of a + in list_div.innerHTML += ..., and (as a consequence) clearing the inner HTML before the loop.
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())
}
})
});
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>