Javascript function is undefined in HTML - javascript

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

Related

Firebase Database Errors

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

how can i transfer the data from my browser console to my php code. I am using a javascript in the browser console

This is the code I am using for the browser console
<!DOCTYPE html>
<html lang="en">
<head>
<title>Firebase</title>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-database.js"></script>
<style type="text/css">
/* Set the size of the div element that contains the map */
#map {
height: 400px;
/* The height is 400 pixels */
width: 100%;
/* The width is the width of the web page */
}
</style>
</head>
<!-- <body>
<div id="root"></div>
</body> -->
This is to connect the browser console to firebase database
<script>
const firebaseConfig = {
apiKey: "AIzaSyD2SevZI0FJV4jew4Z-c9pl7CxntknqEQY",
authDomain: "thesisesp8266.firebaseapp.com",
databaseURL: "https://thesisesp8266-default-rtdb.firebaseio.com",
projectId: "thesisesp8266",
storageBucket: "thesisesp8266.appspot.com",
messagingSenderId: "316864477515",
appId: "1:316864477515:web:56b460e9ce1d3a088550ce",
measurementId: "G-F3SG81M2L6"
};
This is to print the data from database to browser console
firebase.initializeApp(firebaseConfig);
database = firebase.database();
var ref = database.ref('GPS');
ref.on('value', gotData, errData);
function gotData(data){
console.log(data.val());
var GPS = data.val();
var keys = Object.keys(GPS);
console.log(keys);
}
function errData(err){
console.log('Error!');
console.log(err);
}
</script>
</body>
</html>

firebase.auth().onAuthStateChanged() function is called multiple times even after unsubscribing

<!-- 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.

Firebase in Web : A network error (such as timeout, interrupted connection or unreachable host) has occurred?

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

Firebase Web not working

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.

Categories

Resources