Hello I am trying to make a web site utilizing Firebass as my back end but I am having trouble reading data from the data base. I've double checked the paths and yes there is data there. If someone could give a quick look at what I am doing wrong I would really appreciate it. I am not getting any errors, its just not working.
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-database.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app.firebaseio.com",
storageBucket: "my-ap.appspot.com",
messagingSenderId: "123456789"
};
</script>
<script>
function main(){
firebase.initializeApp(config);
var database = firebase.database();
var ratesRef = database.ref("users/rates");
ratesRef.on('child_added', function(snapshot){
console.log("Working");
console.log("lat:" + snapshot.val().latitude);
});
}
</script>
</head>
<body onload="main();">
hello
</body>
</html>
To read from database, you need 2 callbacks, 1 for reading, 1 for errors. This will work for you:
firebase.database().ref("users/rates").once('value', readFn(),errFn(errorObject))
or replace main with this
function main(){
firebase.initializeApp(config);
var database = firebase.database();
var ratesRef = database.ref("users/rates");
ratesRef.on('child_added', function(snapshot){
console.log("Working");
console.log("lat:" + snapshot.val().latitude);
}, function(err) {console.log(err)});
}
You should also use once to prevent reading more than once when you request it
First of all log your errors to see what happens.
ratesRef.once('value')
.then(function(snap){...})
.catch(function(err){console.log(err)})
Very probably you are getting permissions denied error as your security rules by default allow access for authenticated user.
Related
I am trying to make a basic firebase database app and continue to get 3 errors that I don't know how to fix. The errors are:
Uncaught SyntaxError: Unexpected token 'export' (at firebase-app.js:2348:1)
Uncaught SyntaxError: Cannot use import statement outside a module (at firebase-storage.js:1:1)
storage.js:16 Uncaught ReferenceError: firebase is not defined
at storage.js:16:2 ()
at storage.js:58:2
For #3 storage.js:16:2 points to firebase.initializeApp(firebaseConfig) code and storage.js:16:2 point to the } at the end of the code, }());. I have attached my code and images of the errors I am getting. Please help!
(function(){
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyBFZQE-zC4QNu3ooZE7VygTN83g7su-wIc",
authDomain: "courso-43b7d.firebaseapp.com",
databaseURL: "https://courso-43b7d.firebaseio.com",
projectId: "courso-43b7d",
storageBucket: "courso-43b7d.appspot.com",
messagingSenderId: "373899831879",
appId: "1:373899831879:web:d76aa2fbd69529cabb9f62"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// handle on firebase db
var db = firebase.database();
// get elements
var message = document.getElementById('message');
var write = document.getElementById('write');
var read = document.getElementById('read');
var status = document.getElementById('status');
// write
write.addEventListener('click', e => {
var messages = db.ref('messages');
// simple id - ok for example, do not use in production
var id = (new Date).getTime();
// write to db
messages.child(id).set({'message' : message.value})
.then(function(){
status.innerHTML = "Wrote to DB!";
});
});
// read
read.addEventListener('click', e => {
status.innerHTML = '';
var messages = db.ref('messages');
messages.once('value')
.then(function(dataSnapshot) {
var data = dataSnapshot.val();
var keys = Object.keys(data);
keys.forEach(function(key){
console.log(data[key]);
status.innerHTML += JSON.stringify(data[key]) + '<br>';
});
});
});
}());
<!DOCTYPE html>
<html>
<head>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/9.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.8.0/firebase-database.js"></script>
</head>
<input id="message" type="text" placeholder="Text to write to DB"><br>
<button id="write">Write</button>
<button id="read">Read</button><br>
<div id="status"></div>
<script src="database.js"></script>
</html>
Dev Tools SyntaxErrors
<!-- begin snippet: js hide: false console: true babel: false -->
var unSubscribe=firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
window.location.replace("library.html");
var user = firebase.auth().currentUser;
if(user != null){
var email_id = user.email;
//document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
}
} else {
// No user is signed in.
window.location.replace("index.html");
}
unSubscribe();
});
function login(){
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
// ...
});
}
function logout(){
firebase.auth().signOut();
}
<html>
<head>
<title>Firebase Login</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="login_div" class="main-div">
<h3>Firebase Web login Example</h3>
<input type="email" placeholder="Email..." id="email_field" />
<input type="password" placeholder="Password..." id="password_field" />
<button onclick="login()">Login to Account</button>
</div>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-firestore.js"></script>
<script>
// Initialize Firebase
var firebaseConfig = {
apiKey: ,
authDomain: ,
databaseURL: ,
projectId: ,
storageBucket: ,
messagingSenderId:,
appId: ,
measurementId:
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script src="index.js"></script>
</body>
</html>
(library.html also has the same script tags.)
I have seen similar questions and the answers to them were to call the function returned by firebase.auth().onAuthStateChanged(), so I implemented that but the index.html page keeps reloading multiple times. I have implemented the functionality for a single html page by hiding and displaying elements and it worked fine before.
I have also tried inserting the window.location.replace() in the login and logout functions but that on browser gives a blank html page and no errors on inspect.
Please help me with the issue, I am a beginner at javascript and web development.
You say both HTML pages have the same script running. So when you redirect to either page, the code will run again, trying to redirect you again.
If this is indeed the problem, a quick fix might be to pass a query param like redirect=true, and then only execute the code when this param is false.
window.location.replace("library.html?redirect=true");
then parse your url with a regex f.e.
const wasRedirected = new Regex(/[?&]redirect=(true|false)/g).exec(window.location)[1] === 'true'
firebase.auth().onAuthStateChanged() function sets an observer on the Auth Object. And as an observer, it continuously checks for the state of the authorization. That's why the index.html page keeps on reloading. The solution is to call the onAuthStateChanged() function only one time when your window reloads for the first time. Add the following code in the index.js file.
window.onload = unSubscribe;
Hope it helps.
I am trying to execute a simple function to execute what a users email is. If I delete everything in the javascript file besides the function itself everything works just fine, can anyone spot an issue with this code that would cause this to break? How should I initialize firebase in one javascript file so that I can reuse the initialization across multiple files?
HTML:
<head>
<script type="text/javascript" src="/JS/getUsersNameR.js"></script>
</head>
<span>Welcome, <strong><script>usersEmail()</script></strong></span><br>
JS:
var firebase = require("firebase");
var $;
$ = require('jquery');
require("firebase/firestore");
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
var user = firebase.auth().currentUser;
var email;
if (user) {
// User is signed in.
email = user.email;
alert("TEST");
} else {
// No user is signed in.
}
function userEmail() {
document.write("TEST");
}
I guess the path of your js reference is wrong. Double check the path. Otherwise the code looks good
DEMO
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function usersEmail() {
document.write("TEST");
}
</script>
</head>
<body>
<script type="text/javascript">
usersEmail();
</script>
</body>
</html>
don't call the function through a script tag, if you want to call a function when the page loads use the body tag's onload attribute. example:
<body onload="myFunction();"><div id="myText">other code</div></body>
and have the myFunction() function set the text value of a certain id to whatever you want. Example:
function myFunction(){
document.getElementById("myText").innerHTML = "My text";
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
console.log("Hurray ! signed in successfully !");
} else {
// No user is signed in.
console.log("Sign in required !");
$("#login-btn-nav").click();
}
});
$("#login-btn").on('click',function(){
console.log("Hello");
var email = $("#email-input").val();
var password = $("#password-input").val();
if(email != "" && password != ""){
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
window.alert("Following error encountered : "+errorMessage+" .");
});
}
});
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyDAvfWcdBTtmDbK7_aOkWFCRxNl1K4PDck",
authDomain: "sarahhah-8e315.firebaseapp.com",
databaseURL: "https://sarahhah-8e315.firebaseio.com",
projectId: "sarahhah-8e315",
storageBucket: "sarahhah-8e315.appspot.com",
messagingSenderId: "965679781332"
};
firebase.initializeApp(config);
console.log(config);
</script>
<script type="text/javascript" src="assets/js/login.js"></script>
copied the web code snipets ans pasted in the html code as attached and javascript code is also attached !
facing error as :
A network error (such as timeout, interrupted connection or unreachable host) has occurred. .
in web integration of firebase
thanks in advance for your cooperation
I will duplicate an answer from comments from Rahul Sharma because this saved me a lot of time. Hope this will help somebody else:
Use <div> instead of <form> tag
I am new to JavaScript and Google BigQuery, so please forgive my ignorance. I am trying to write a javascript to collect data from one of the public databases on BigQuery. I found an answer to this at Obtaining BigQuery data from JavaScript code (the code for which I have pasted below) but when I saved the file as .html, replaced the client id and project number with mine, and tried to run it, I get the Authorize button and the page title. I click the Authorize button, and it disappears, but no query is run. Is there something else I was supposed to replace or is there something else I need to make this work? I saved the file as a .html, perhaps I should have saved it with a different extension?
I tried all three ways of creating a client id in the Google developers console and all gave me the same behavior.
I'm sure its just something silly that I am forgetting, but any advice would be greatly appreciated.
Here is the code given by Ryan Boyd, which I am unable to get working properly(which is surely my fault):
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = '605902584318';
var client_id = '605902584318.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
Update: I opened the Developer Tools in Chrome and found this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin
provided ('file://') does not match the recipient window's origin
('null')
.
I tried editing in my Google Developer console as per these instructions: Google API in Javascript
Still same error.
Looks like you may need to add:
$('#query_button').show();
to the bottom of the auth() function
like so:
function auth() {
gapi.auth.authorize(config, function()
{
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
$('#query_button').show();
}
Searching for the error you got, I found this page:
Google API in Javascript
Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID. --#citizenslave
It turns out it was a combination of things. I had the Javascript origin not configured properly, I didn't have all the scopes needed for my query, and I couldn't just open the html file in a browser, I needed to create an HTTP server.
So I changed the code to be:
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
I fixed my Google Javascript Origins url to be http://localhost:8888/ and my Redirect uri to be http://localhost:8888/oauth2callback, opened a command prompt to run this command from the directory of my html file:
python -m SimpleHTTPServer 8888
and then went to localhost:8888 in my browser and clicked my html file there.
Thanks so much for all the feedback!
It worked perfectly! Now to change the query for my purposes!