I am trying to write a website, but when I try to call a JavaScript function defined in another file from my HTML code I get the following error
Uncaught ReferenceError: fetchConfs is not defined at admin.html:46
I did import the script in the <head> portion of the HTML, but for some reason, I am still getting the error.
admin.html:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="bundle.css">
<script type="text/javascript" src="bundle.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-firestore.js"></script>
<title>Dilo+</title>
</head>
<header class="header">
<img src="logo.png">
<p>Sobreviviendo a lo imposible</p>
</header>
<body>
<script type="text/javascript">
var firebaseConfig = {
apiKey: "",
authDomain: "dilo-mas.firebaseapp.com",
databaseURL: "https://dilo-mas.firebaseio.com",
projectId: "dilo-mas",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(firebaseConfig);
initApp = function () {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
var email = user.email;
user.getIdToken().then(function (accessToken) {
document.getElementById("greeter").textContent = "Hola " + email;
});
} else {
window.location.href = '/login.html'
}
}, function (error) {
console.log(error);
});
};
window.addEventListener('load', function () {
initApp()
document.getElementById("logout").onclick = function logout() {
firebase.auth().signOut().then(function () { window.location.href = '/login.html' });
}
var confs = fetchConfs();
});
</script>
<h1 id="greeter">Error, inicia sesión para continuar</h1>
<button class="mdc-button foo-button" id="logout" style="float: right;">
Cerrar Sesión
</button>
</body>
</html>
app.js (This file is compiled to bundle.js using webpacks before deploying):
import {MDCRipple} from '#material/ripple/index';
import { MDCTextField } from '#material/textfield';
import * as firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/firebase-auth';
const ripple = new MDCRipple(document.querySelector('.foo-button'));
var firebaseConfig = {
apiKey: "",
authDomain: "dilo-mas.firebaseapp.com",
databaseURL: "https://dilo-mas.firebaseio.com",
projectId: "dilo-mas",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(firebaseConfig);
document.getElementById("tbut").onclick = function submitForm() {
var date = Date.now().toString()
var x = document.getElementById("conf").value;
firebase.firestore().collection("confesiones").doc(date).set({
conf: x
})
.then(function () {
console.log("Document successfully written!");
var y = document.getElementById("conf").value;
console.log("input " + x)
alert("Exito");
})
.catch(function (error) {
console.error("Error writing document: ", error);
alert("Error envíando tu confesión")
});
document.getElementById("conf").reset();
}
function fetchConfs() {
var confs = db.collection("confesiones").where(firebase.firestore.FieldPath.documentId(), "!=", "root").get();
return confs;
}
I already tried assigning fetchConfs() to the window object or to a global variable, but I'm still getting the same error.
Note: I am using webpacks and other npm plugins to compile js and sass code to static files for deployment.
Scripts are run in the order that they are listed in <head>, then any in the body. If the function is in a script listed later, that function may not be defined yet when it is run.
To fix this, define fetchConfs earlier on.
Related
I get the data of all the movies on my home page. But I don't want to do this on the Admin.html page. On the admin page, when I click on the name of the movie, I want to go to the page related to that movie. For example, when I click on the movie "Schindler's List" which movieId is 3 (Admin.html?movieId=3), I want to go to a page with only Schindler's List movie information. It will show only Schindler List's img,score,name. How can I achieve this?
Admin.html
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import { getDatabase, set, ref, update, get, child } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);
btnCreate.addEventListener('click',(e)=>{
var movieId = document.getElementById('movieId').value;
var movieName = document.getElementById('movieName').value;
var movieScore = document.getElementById('movieScore').value;
var movieImage = document.getElementById('movieImage').value;
set(ref(db, 'Movies/' + movieId), {
movieId: movieId,
movieName: movieName,
movieScore: movieScore,
movieImage : movieImage
});
});
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name,score,img,id){
let html='';
const movies=`
<div class="content"><img src="${img}"><p>${name}</p> <p> <img src="img/mutlu.png" class="emoji"><a class="scoretxt">${score}</a> </p> </div>
`;
html = movies;
body.innerHTML += html;
body2.innerHTML+=html;
}
function AddAllItemsToTable(TheMovies){
body.innerHTML="";
TheMovies.forEach(element => {
AddItemsToTable(element.movieName, element.movieScore, element.movieImage,element.movieId);
});
}
function getAllDataOnce(){
const dbRef=ref(db);
get(child(dbRef,"Movies"))
.then((snapshot)=>{
var movies=[];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload= getAllDataOnce;
The problem is that the onlclick returns "main.html:1 Uncaught ReferenceError: removePost is not defined at HTMLButtonElement.onclick (main.html:1)" I need to load the function removePost to erase the post with the specific id. After that I tried the same trick but with the eventListener (see in the final of the code) but returns null, the html reference it seems to be out of scope. Uncaught TypeError: Cannot read property 'addEventListener' of null at main.js:70.
Any ideas? thx in advance.
HTML
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<title>Count Likes</title>
</head>
<body>
<div class="root"></div>
<div class="CountLike" id="Like Count">
<button class="button button1">
<i class="fa fa-heart"></i> Like <span class="counterStat">...</span>
</button>
</div>
<div class="formContainer">
<input id="nameInput" type="text" placeholder="Escribe tu nombre" />
<input id="bodyInput" type="text" placeholder="Ingresa comentario" />
<button id="btnSend">Publicar</button>
</div>
<table class="table">
<tbody id="table"></tbody>
</table>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-firestore.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyBoHBd8UGJ2oFxyEu9lqbIWmg_j-MvcYZQ",
authDomain: "like-button-2203f.firebaseapp.com",
databaseURL: "https://like-button-2203f-default-rtdb.firebaseio.com",
projectId: "like-button-2203f",
storageBucket: "like-button-2203f.appspot.com",
messagingSenderId: "949206080621",
appId: "1:949206080621:web:8b2146c19e8c082b913364",
measurementId: "G-REJZ56MGNY",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// firebase.analytics();
</script>
<script type="module" src="main.js"></script>
</body>
</html>
JAVASCRIPT
const db = firebase.firestore();
const dCounters = document.querySelectorAll(".CountLike");
[].forEach.call(dCounters, function (dCounter) {
const el = dCounter.querySelector("button");
const cId = dCounter.id;
const dDatabase = firebase.database().ref("Like Number Counter").child(cId);
// get firebase data
dDatabase.on("value", function (snap) {
const data = snap.val() || 0;
dCounter.querySelector("span").innerHTML = data;
});
// set firebase data
el.addEventListener("click", function () {
dDatabase.transaction(function (dCount) {
return (dCount || 0) + 1;
});
});
});
document.getElementById("btnSend").addEventListener("click", () => {
let name = document.getElementById("nameInput").value;
let body = document.getElementById("bodyInput").value;
db.collection("post")
.add({
name: name,
body: body,
})
.then(function (docRef) {
console.log("id ", docRef.id);
document.getElementById("nameInput").value = "";
document.getElementById("bodyInput").value = "";
})
.catch(function (error) {
console.error("Error ", error);
});
});
const table = document.getElementById("table");
db.collection("post").onSnapshot((querySnapshot) => {
table.innerHTML = "";
querySnapshot.forEach((doc) => {
// console.log(`${doc.id}=>${doc.data().name}`);
table.innerHTML += `
<tr>
<th scope='row'>${doc.id}</th>
<td>${doc.data().name}</td>
<td>${doc.data().body}</td>
<td><button onclick="removePost('${doc.id}')"
id="btnRemove" class="far fa-trash-alt"></button></td>
<td><button id="editPost" class="far fa-edit"></button></td>
</tr>`;
});
});
function removePost(id) {
db.collection("post")
.doc(id)
.delete()
.then(function () {
console.log("Removed");
})
.catch(function (error) {
console.error("Error - " + error);
});
}
EventListener
document.getElementById("btnRemove").addEventListener("click", (evt) => {
db.collection("post")
.doc(evt.target.doc.id)
.delete()
.then(function () {
console.log("Removed");
})
.catch(function (error) {
console.error("Error - " + error);
});
});
var file;
/////detect if file is upload/////////
$("#file").on('change',function(e){
file = e.target.files[0];
});
/////function for upload to storage button when clicked///////////
function uploadFile(){
var storageRef = firebase.storage().ref('/pics/'+file.name);
var task = storageRef.put(file);
console.log("yes");
}
On my side, below code is working well, and that is almost the same as the question code.
<html>
<header>
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var config = {
apiKey: " ",
authDomain: " ",
databaseURL: " ",
projectId: " ",
storageBucket: " ",
messagingSenderId: " "
};
firebase.initializeApp(config);
$(document).ready(function () {
var file;
$("#file").on('change', function (e) {
file = e.target.files[0];
});
$('#btnUpload')
.click(function () {
if (file == null || file.name == null) {
alert("Please select file");
return;
}
var storageRef = firebase.storage().ref('/pics/' + file.name);
var task = storageRef.put(file)
.then((snapshot) => {
console.log('Uploaded a blob or file!', snapshot);
})
.catch(error => {
console.error(error)
});
});
});
</script>
</header>
<body>
<h3>Upload File</h3>
<div>
<input type="file" id="file" class="form">
<button class="btn btn-danger" id="btnUpload">Upload</button>
</div>
</body>
</html>
Updated:
Only added then, catch for debug.
But, working well.
var task = storageRef.put(file)
.then((snapshot) => {
console.log('Uploaded a blob or file!', snapshot);
})
.catch(error => {
console.error(error)
});
I was following this video from the Firebase Team to add Firebase Auth to my application (https://www.youtube.com/watch?v=-OKrloDzGpU)
I have added the web application script generated for my project in Firebase into the html section of my app and basically copied the other code to do the login and signing up as seen in the code below
But I got this error which I have no idea why its triggering
TypeError: auth.signInWithEmailandPassword is not a function. (In 'auth.signInWithEmailandPassword(email, pass)', 'auth.signInWithEmailandPassword' is undefined)
HTML Code
<!DOCTYPE html> <meta charset="utf-8" />
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-auth.js"></script>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" required placeholder="Email" />
<input id="txtPassword" type="password" required placeholder="Password" />
<button id="btnLogin" class="button-is-link">Login</button>
<button id="btnSignUp" class="button-is-info">Sign Up</button>
</div>
<script src="js/auth.js"></script>
</body>
</html>
Auth.js
(function() {
// Initialize Firebase
var config = {
apiKey: 'API KEY',
authDomain: 'DOMAIN',
databaseURL: 'DATABASE',
projectId: 'ID',
storageBucket: 'BUCKET',
messagingSenderId: 'ID'
};
firebase.initializeApp(config);
const txtEmail = document.getElementById('txtEmail');
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnSignUp = document.getElementById('btnSignUp');
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailandPassword(email, pass);
promise.catch(e => console.log('e.message'));
});
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.createUserWithEmailandPassword(email, pass);
promise.catch(e => console.log('e.message'));
firebase.auth().onAuthStateChange(firebaseUser => {
if (firebaseUser) {
console.log('U are logged in');
} else {
console.log('Not logged in');
}
});
});
})();
The exact method name is signInWithEmailAndPassword, with an upper case "A" at And.
It is the same with createUserWithEmailAndPassword.
run given below command, Before execute make sure to delete "package-lock.json"
npm i #angular/fire#latest --save
I am trying to retrieve the data from firebase database.
And I can connect to firebase auth and check currentUser data, it's fine.
But I can't retrieve the data from firebase database, it just return the empty array.
firebase version = 5.0.4
vue version = 2.5.16
The database structure
users/
--------uId/
--------------name
--------------email
Vue Js folder structure
App.vue
firebase.js
main.js
components /
------------ Home.vue
firebase.js
var firebase = require('firebase');
require("firebase/auth");
require("firebase/database");
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config)
export const auth = firebase.auth();
export const db = firebase.database()
Home.vue
<script>
import {db} from './../firebase';
import {auth} from './../firebase';
var usersRef = db.ref('users');
export default {
name: "Home",
components: {
add_new
},
data(){
return {}
},
mounted: function(){
console.log(usersRef);
var userId = auth.currentUser.uid;
return db.ref('/users/' + userId).once('value').then(function(snapshot) {
snapshot.forEach(function (childData) {
console.log(childData.val())
})
})
}
}
</script>
Here, Vue app works correctly,
only the firebase.database ( usersRef ) returns the empty array.
This is the screenshot of console.log(usersRef) result
https://i.stack.imgur.com/NH7gh.png
First instead of using multiple import statements, why not
import {auth, db} from './../firebase';
And try to change
snapshot.forEach(function (childData) {
console.log(childData.val())
})
to snapshot.val()
var userId = auth.currentUser.uid;
return db.ref('/users/' + userId).once('value').then(function(snapshot) {
console.log(snapshot.val());
});