I have simple login form on my website. I am using firebase authentication to authenticate users. So far I can create a user successfully with the signup form. However, when I try to log them in with the created credentials nothing happens. Not even when I press the login button. There should be an error message on the login form if you try and click submit without entering any data into the fields but even that does not work. Could it be a getElementById problem? Kindly help me out. PS: You can test out logging in with a user I created: username: test#google.com password: helloworld
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.4/css/bulma.min.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Website</title>
<link rel="stylesheet" href="./style.css" type="text/css">
<link rel="icon" href="./favicon.ico" type="image/x-icon">
</head>
<body>
<main>
<!--Login -->
<section>
<div class="hero is-fullheight">
<div class="hero-body is-justify-content-center is-align-items-center">
<div class="columns is-flex is-flex-direction-column box">
<div class="column">
<h1 class="title">Please enter your credentials</h1>
<label for="email">Email</label>
<input id="login-email" class="input is-primary" type="text" placeholder="Email address">
</div>
<div class="column">
<label for="Name">Password</label>
<input id="login-pwd" class="input is-primary" type="password" placeholder="Password">
forget password?
</div>
<div class="column">
<button id="login-btn" class="button is-primary is-fullwidth" type="submit">Login</button>
</div>
<div class="has-text-centered">
<p class="is-size-7"> Don't have an account? Sign up
</p>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- Firebase Auth -->
<script type="module" src="index.js">
//FIREBASE AUTH
// Import the functions you need from the SDKs you need
import {
initializeApp
} from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import {
getDatabase,
set,
ref,
update
} from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword
} from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyAalz5fFuOOG6_EZVFIO-hJRA2Sw1Yyg2A",
authDomain: "lost-and-found-system-67568.firebaseapp.com",
databaseURL: "https://lost-and-found-system-67568-default-rtdb.firebaseio.com",
projectId: "lost-and-found-system-67568",
storageBucket: "lost-and-found-system-67568.appspot.com",
messagingSenderId: "32608786023",
appId: "1:32608786023:web:6aea01187ecb53ce6a66c2"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth();
signup.addEventListener('click', (e) => {
var username = document.getElementById('signup-user').value;
var email = document.getElementById('signup-email').value;
var schoolID = document.getElementById('signup-id').value;
var password = document.getElementById('signup-pwd').value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
set(ref(database, 'user/' + user.id), {
username: username,
email: email
})
alert('User Created!');
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert('Error!');
// ..
});
});
//login section
login-btn.addEventListener('click', (e) => {
var email = document.getElementById('login-email').value;
var password = document.getElementById('login-pwd').value;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const dt = new Date();
update(ref(database, 'user/' + user.id), {
last_login: dt,
})
alert('User logged In!');
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
});
</script>
</body>
</html>
Related
I am setting up a comment board for an assignment and I have been given the following instructions. I have tried every method I can think of to implement this feature but I am quite lost.
When the “post” button is clicked, a JavaScript event handler should
handle the onClick event and store the user inputted comment data into
an object. To get the data inputted into the text boxes, the “value”
property can be used. Thus if you have set the ID attribute on the
element to “myElement”, then you can simply call “myElement.value” to
retrieve the value.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Comment section</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="alert"> Your message has been sent</div>
<h1> Spartak Swinford FC - Comment Section</h1>
<form id=contactform" action="#"
<fieldset>
<legend>Message</legend>
<span>Email: </span><input id="email" required type="email"><br>
<span>Handle: </span><input id="name" required type="name"><br>
<span style="position: absolute;"></span>
<textarea name="message" id="message" cols="50" rows="8">Enter your message...</textarea>
<br>
<button id="btn" type="submit" onclick="sendMessage()">Post</button>
</fieldset>
</form>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-analytics.js";
</script>
<script src="code.js"></script>
</body>
</html>
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyDTQHqdMoOmS1doN_bog-SA8e4rPeGAz-s",
authDomain: "assignment4-9652f.firebaseapp.com",
projectId: "assignment4-9652f",
storageBucket: "assignment4-9652f.appspot.com",
messagingSenderId: "103112042140",
appId: "1:103112042140:web:e0e5b4dbfedc3039776f59",
measurementId: "G-SYBJLVNBCK"
};
JavaScript
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
var database=firebase.database();
function sendMessage()
{
//getting the required values to send to firebase database and saving
//them in the variables
var email=document.getELementById("email").value;
var name=document.getElementById("name").value;
var message=document.getElementById*"message");
var newMessagekey=database.ref().child("comments").push().key;
database.ref("comments/"+newMessagekey+"/Email").set(email);
database.ref("comments/"+newMessagekey+"/Name").set(name);
database.ref("comments/"+newMessagekey+"/message").set(message);
}
</script>
document.getElementByID("contactForm") addEventListener("submit", submitForm)
function submitForm(e)
{
e.preventDefault();
}
document querySelector('alert').getElementByClassName.display="block";
function hideAlert()
{
document.querySelecto(".alert").getElementsByClassName,display="none";
}
setTimeout(hideAlert,3000);
This question already has an answer here:
Why there's error in onclick when i have "module" in script tag?
(1 answer)
Closed 8 months ago.
I was trying a call an async function using the onsubmit event of an HTML form. But unfortunately, I am getting this error...
Here is my HTML code...
<!DOCTYPE html>
<html lang="en">
<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">
<title>To-Do App</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script type="module" src="./script.js"></script>
</head>
<body>
<div class="background-image">
<img src="./assets/bg-desktop-dark.jpg">
</div>
<div class="container">
<div class="header">
<div class="title">
TODO
</div>
<div class="theme">
<img src="./assets/icon-sun.svg" alt="">
</div>
</div>
<div class="new-todo">
<div class="check">
<div class="check-mark">
</div>
</div>
<div class="new-todo-input">
<form onsubmit="addItem(event)">
<input id="todo-input" type="text" placeholder="Create a new todo...">
</form>
</div>
</div>
<div class="todo-items-wrapper">
<div class="todo-item">
<div class="check">
<div class="check-mark">
<img src="./assets/icon-check.svg">
</div>
</div>
<div class="todo-text">
Default Todo Text
</div>
</div>
<div class="todo-items-info">
<div class="items-left">
5 items left
</div>
<div class="items-statuses">
<span class="active">All</span>
<span>Active</span>
<span>Completed</span>
</div>
<div class="items-clear">
<span>Clear Completed</span>
</div>
</div>
</div>
</div>
</body>
</html>
Here is my Javascript code...
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.4/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.8.4/firebase-analytics.js";
import { getFirestore, collection, addDoc } from "https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js";
const firebaseConfig = {
apiKey: "api_key",
authDomain: "auth_domain",
projectId: "project_id",
storageBucket: "storage_bucket",
messagingSenderId: "messagin_sender_id",
appId: "add_id",
measurementId: "measurement_id"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
async function addItem(event)
{
event.preventDefault();
let text = document.getElementById("todo-input");
try
{
const docRef = await addDoc(collection(db, "todo-items"), {
text: text.value,
status: "active"
});
console.log("Document written with ID: ", docRef.id);
}
catch (e)
{
console.error("Error adding document: ", e);
}
}
Please tell me how can I fix this...........................................................
As the error shows, the "addItem" function doesn't exist.
Maybe the script file hasn't been inserted in the HTML.
The error message tells you that addItem is missing. Even though you have created it and it exists in a file, it does not exist in your page when you call it. Since your script has a type of module, you need to import it, like:
import addItem from ./script.js
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
However, to make sure that this works, you need to export your addItem function.
I created simple website in order to learn Firebase 9, but it doesn't work properly when I try to import any of firebase files.
I've looked for tutorials how to config firebase, but they either don't solve my problem or are about the older (thus completely different) version of firebase.
In index.js I added window.alert("OK"); in order to know whether my code works. It does, but only when I comment all the import firebase lines (or at least the one in index.js).
I think I have installed npm and firebase correctly, but I'll add the screenshot of my folder (maybe something should be in different direction (?)).
My folder:
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>User portal</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto">
<script src="index.js"></script>
</head>
<body>
<div class="card" id="login">
<div class="paragraph">
<div class="header">Hi!</div>
<p>Sign up or Sign in!</p>
</div>
<div class="inputs">
<div>
E-mail:
<br>
<input class="input" id="userEmail" type="text" name="email" value="" placeholder="Aa">
<p>
Password:
<br>
<input class="input" id="userPass" type="password" name="pass" value="" placeholder="Aa">
</p>
</div>
<p>
<button class="button" onclick="logIn()">
Log in!
</button>
</p>
</div>
</div>
<div class="card" id="logged-in">
<div class="paragraph">
<div class="header">Hi!</div>
<p>Welcome to your account!</p>
</div>
<div class="inputs">
<p>
<button class="button" onclick="logOut()">
Log out!
</button>
</p>
</div>
</div>
<script type="module" src="load.js"></script>
</body>
</html>
index.js:
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
function logIn() {
window.alert("OK");
var uE = document.getElementById("userEmail").value;
var uP = document.getElementById("userPass").value;
}
function logOut() {
document.getElementById("login").style.display = "block";
document.getElementById("logged-in").style.display = "none";
}
load.js:
import { initializeApp } from 'firebase/app';
import { getAnalytics } from "firebase/analytics";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyCOyINuV-Ppeq8ShseJiTOVGS7_ZU9SiTg",
authDomain: "login-9e245.firebaseapp.com",
projectId: "login-9e245",
storageBucket: "login-9e245.appspot.com",
messagingSenderId: "926078358623",
appId: "1:926078358623:web:2a0fa27e6f9066cec037ea",
measurementId: "G-DKKZ0632PT"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
Please help me with it, because I want to learn something.
I suggest trying a frontend tooling library like Vite.
# npm 6.x
npm create vite#latest my-vue-app --template vanilla
# npm 7+, extra double-dash is needed:
npm create vite#latest my-vue-app -- --template vanilla
# yarn
yarn create vite my-vue-app --template vanilla
# pnpm
pnpm create vite my-vue-app -- --template vanilla
I think you're having the same issue as the following thread:
Your using npm without a bundler. Try importing firebase like in the thread below.
Firebase 9 modular -how to start
Here is the basic boilerplate that works when serving locally:
index.js:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';
const firebaseApp = initializeApp({
// (insert your Firebase configuration here)
});
const auth = getAuth(firebaseApp);
onAuthStateChanged(auth, user => {
if (user) {
console.log('Logged in as ${user.email}' );
} else {
console.log('No user');
}
});
HTML
<!DOCTYPE html>
<html lang="en">
<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">
<title>Getting started with Firebase Auth</title>
<script type="module" src="/index.js"></script>
</head>
<body>
</body>
</html>
EDIT: I kind of got your code working. I changed both your scripts to modules and instead of exporting the logout and login functions I used event listeners on the buttons
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>User portal</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" />
<script type="module" src="index.js"></script>
</head>
<body>
<div class="card" id="login">
<div class="paragraph">
<div class="header">Hi!</div>
<p>Sign up or Sign in!</p>
</div>
<div class="inputs">
<div>
E-mail:
<br />
<input class="input" id="userEmail" type="text" name="email" value="" placeholder="Aa" />
<p>
Password:
<br />
<input class="input" id="userPass" type="password" name="pass" value="" placeholder="Aa" />
</p>
</div>
<p>
<button class="button login">Log in!</button>
</p>
</div>
</div>
<div class="card" id="logged-in">
<div class="paragraph">
<div class="header">Hi!</div>
<p>Welcome to your account!</p>
</div>
<div class="inputs">
<p>
<button class="button logout">Log out!</button>
</p>
</div>
</div>
<script type="module" src="load.js"></script>
</body>
</html>
load.js:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getAnalytics } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-analytics.js';
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: 'AIzaSyCOyINuV-Ppeq8ShseJiTOVGS7_ZU9SiTg',
authDomain: 'login-9e245.firebaseapp.com',
projectId: 'login-9e245',
storageBucket: 'login-9e245.appspot.com',
messagingSenderId: '926078358623',
appId: '1:926078358623:web:2a0fa27e6f9066cec037ea',
measurementId: 'G-DKKZ0632PT',
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export default app;
index.js:
import { getAuth, onAuthStateChanged, signInWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js';
import app from './load.js';
document.querySelector('.login').addEventListener('click', () => {
window.alert('OK');
const auth = getAuth(app);
onAuthStateChanged(auth, (user) => {
if (user) {
console.log('Logged in as ${user.email}');
} else {
console.log('No user');
}
});
var uE = document.getElementById('userEmail').value;
var uP = document.getElementById('userPass').value;
});
document.querySelector('.logout').addEventListener('click', () => {
document.getElementById('login').style.display = 'block';
document.getElementById('logged-in').style.display = 'none';
});
I was able to create an account in your config using the following code.
Dont forget to install vite using:
npm create vite#latest firebasedemo --template vanilla
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>User portal</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" />
</head>
<body>
<div class="card" id="login">
<div class="paragraph">
<div class="header">Hi!</div>
<p>Sign up or Sign in!</p>
</div>
<div class="inputs">
<div>
E-mail:
<br />
<input class="input" id="userEmail" type="text" name="email" value="" placeholder="Aa" />
<p>
Password:
<br />
<input class="input" id="userPass" type="password" name="pass" value="" placeholder="Aa" />
</p>
</div>
<p>
<button class="button login">Log in!</button>
<button class="button create">Create Account</button>
</p>
</div>
</div>
<div class="card" id="logged-in">
<div class="paragraph">
<div class="header">Hi!</div>
<p>Welcome to your account!</p>
</div>
<div class="inputs">
<p>
<button class="button logout">Log out!</button>
</p>
</div>
</div>
<script src="./main.js" type="module"></script>
</body>
</html>
main.js
import './style.css';
import app from './firebaseConfig';
import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth';
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/todos/1').then((res) => {
console.log(res);
});
document.querySelector('.create').addEventListener('click', () => {
var uE = document.getElementById('userEmail').value;
var uP = document.getElementById('userPass').value;
const auth = getAuth();
createUserWithEmailAndPassword(auth, uE, uP)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log('logged in');
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
});
document.querySelector('.login').addEventListener('click', () => {
var uE = document.getElementById('userEmail').value;
var uP = document.getElementById('userPass').value;
});
document.querySelector('.logout').addEventListener('click', () => {
document.getElementById('login').style.display = 'block';
document.getElementById('logged-in').style.display = 'none';
console.log('test2');
});
firebaseConfig.js
import { initializeApp } from 'firebase/app';
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
apiKey: 'AIzaSyCOyINuV-Ppeq8ShseJiTOVGS7_ZU9SiTg',
authDomain: 'login-9e245.firebaseapp.com',
projectId: 'login-9e245',
storageBucket: 'login-9e245.appspot.com',
messagingSenderId: '926078358623',
appId: '1:926078358623:web:2a0fa27e6f9066cec037ea',
measurementId: 'G-DKKZ0632PT',
};
const app = initializeApp(firebaseConfig);
export default app;
package.json:
{
"name": "firebasedemo",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"vite": "^2.9.2"
},
"dependencies": {
"axios": "^0.26.1",
"firebase": "^9.6.11"
}
}
I'm building a register form in nodejs. Once I save the user to a database and i try to redirect to another html page I get an error "SyntaxError: Unexpected token < in JSON at position 0". Could anyone help me out with it.If i console.log the user it appears, but if i try to redirect it doesn't work I make use of a express router to to route my requests.
Here is my code
const express = require("express");
const app = express();
const router = express.Router();
const path = require("path");
const bcrypt = require("bcryptjs");
const { registerValidation } = require("../models/validation");
const User = require("../models/user");
var appDir = path.dirname(require.main.filename);
app.use(express.static(path.join(__dirname, "public")));
router.get("/", (req, res) => {
res.sendFile(appDir + "/public/index.html");
});
router.get("/homepage", (req, res) => {
res.sendFile(appDir + "/public/homepage.html");
});
router.get("/register", (req, res) => {
res.sendFile(appDir + "/public/register.html");
});
router.post("/register", async (req, res) => {
const { error } = await registerValidation.validate(req.body);
if (error) return res.status(400).send(error);
let emailExist = await User.findOne({ email: req.body.email });
if (emailExist) {
return res.status(400).send({ message: "Email already exists" });
}
let salt = await bcrypt.genSalt(10);
let hashedPassword = await bcrypt.hash(req.body.password, salt);
let newUser = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: hashedPassword,
});
try {
let savedUser = await newUser.save();
res.redirect("/homepage");
} catch (err) {
return res.status(400).send(err);
}
});
module.exports = router;
Home page Router
router.get("/homepage", (req, res) => {
res.sendFile(appDir + "/public/homepage.html");
});
homepage.html
<!DOCTYPE html>
<html lang="en">
<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" />
<title>Document</title>
</head>
<body>
<p>This is homepage</p>
</body>
</html>
Register Page
<!DOCTYPE html>
<html lang="en">
<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 rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="./css/register.css" />
<title>Register</title>
</head>
<body>
<section>
<div class="register-container">
<header class="header-text">
Register today to become a movie nerd!!
<hr />
</header>
<form method="POST" name="register-form" id="register-form">
<div class="register-form">
<div class="name-field">
<div class="name-input-container">
<input
type="text"
name="firstName"
class="form-input"
id="firstName"
value="Kevin"
required
placeholder="First Name "
/>
</div>
<div class="name-input-container">
<input
type="text"
name="lastName"
class="form-input"
id="lastName"
placeholder="Last Name "
required
value="Rodrigues"
/>
</div>
</div>
<div class="email-input-container">
<input
type="email"
name="email"
class="form-input"
id="email"
placeholder="Email "
value="kevinrodrigues43#gmail.com"
required
/>
</div>
<div class="password-field">
<div class="password-input-container">
<input
type="password"
name="password"
class="form-input"
id="password"
value="Kevinr78"
required
placeholder="Passsword "
/>
</div>
<div class="name-input-container">
<input
type="password"
name="confirmPassword"
class="form-input"
id="C_password"
placeholder="Confirm Password "
value="Kevinr78"
required
/>
</div>
</div>
<div class="error">
<p id="error"></p>
</div>
<div class="register-button">
<button type="button" id="register-button">Register</button>
</div>
</div>
</form>
</div>
</section>
<script>
document
.getElementById("register-button")
.addEventListener("click", async (e) => {
let formData = validation(e);
let response = await fetch("http://localhost:3000/register", {
method: "POST",
body: JSON.stringify(formData),
headers: {
"Content-type": "application/json;charset=UTF-8",
},
})
.then((data) => {
return data.json();
})
.then((data) => {
console.log(data);
const { message } = data;
document.getElementById("error").innerHTML = message;
})
.catch((err) => {
document.getElementById("error").innerHTML = err;
});
});
function validation(e) {
let email = document.getElementById("email").value;
let lastName = document.getElementById("lastName").value;
let firstName = document.getElementById("firstName").value;
let password = document.getElementById("password").value;
let confirmPassword = document.getElementById("C_password").value;
let emailRegex = "^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+$";
let error = "";
if (
firstName == "" ||
lastName == "" ||
password == "" ||
confirmPassword == "" ||
email == ""
) {
error += "<p>PLease fill all the fields</p>";
}
if (firstName.length < 2 || lastName.length < 2) {
error += "<p>Length of name field is minimum 2 characters</p>";
}
/* if (password != confirmPassword) {
error += "<p>Password Don't match</p>";
} */
if (!email.match(emailRegex)) {
error += "<p>Invalid Email</p>";
}
if (error == "") {
return { lastName, password, firstName, email, confirmPassword };
} else {
document.getElementById("error").innerHTML = error;
}
}
</script>
</body>
</html>
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x"
crossorigin="anonymous"
/>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="./css/index.css" />
<title>Movies Bay</title>
</head>
<body>
<section>
<nav class="nav-container">
<div class="brand-name">
<h3 href="#">Movies Bay</h3>
</div>
<div class="nav-items">
<div class="nav-item">
Login
</div>
<div class="nav-item">
Register
</div>
</div>
</nav>
<div class="main-content">
<h2 id="intro-text"></h2>
<br />
<h4>Your one stop destination for movies</h4>
</div>
<footer>
<p class="text-1">Made By Kevin Rodrigues</p>
<p class="text-2">© 2020-2021</p>
</footer>
</section>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
crossorigin="anonymous"
></script>
<script>
function printLetterByLetter(destination, message, speed) {
let element = document.getElementById(destination);
element.style.fontSize = "4.5em";
var i = 0;
var interval = setInterval(function () {
element.innerHTML += message.charAt(i);
i++;
if (i > message.length) {
clearInterval(interval);
}
}, speed);
}
printLetterByLetter("intro-text", "Welcome to Movies bay", 100);
</script>
</body>
</html>
I am a beginner with html and js. I have the following error when I try to signup a new user. None of the issues found on the internet helped me to find the solution:
Uncaught TypeError: Cannot read property 'close' of undefined
at auth.js:22
at r.g (auth.js:19)
at Dt (auth.js:22)
at Ct (auth.js:22)
at mt.t.Ub (auth.js:21)
at vt (auth.js:15)
Here is the index.html:
<html>
<head>
<title> First test </title>
<!-- Load library: The core Firebase JS SDK is always required and must be listed first -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.css">
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<!-- Load library: Add additional services you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-firestore.js"></script>
<!-- Load library: Authentification -->
<script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-auth.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
var firebaseConfig = {
apiKey: "**********",
authDomain: "**********",
databaseURL: "************",
projectId: "**********",
storageBucket: "****************",
messagingSenderId: "**********"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var firestore = firebase.firestore();
firestore.settings({
timestampsInSnapshots: true
});
const auth = firebase.auth();
</script>
</head>
<!-- Authentificate a new user -->
<div id="modal-signup" , class='modal'>
<div class='modal-content'>
<h4> Sign Up </h4><br />
<form id='signup-user'>
<div class='input-field'>
<input type='email' id="signup-email" />
<label for='signup-email'> email adress </label>
</div>
<div class='input-field'>
<input type='password' id="signup-password" />
<label for='signup-password'> password </label>
</div>
<button id='signup-button' type='submit'>sign up</button>
</form>
</div>
</div>
<script src='./auth.js'></script>
</html>
<!-- <script src="https://www.gstatic.com/firebasejs/5.0.1/firebase-storage.js"></script> -->
And the auth.js script
// values from the firebase console
const signupForm = document.querySelector('#signup-user');
// Sign up function
signupForm.addEventListener("submit", (e) => {
e.preventDefault(); // avoid the page to refresh when we click signup
// get user info from the id of the input
const email = signupForm['signup-email'].value;
const password = signupForm['signup-password'].value;
auth.createUserWithEmailAndPassword(email, password).then( cred => {
console.log(cred);
const modal = document.querySelector('#modal-signup');
console.log(modal)
M.Modal.getInstance(modal).close();
signupForm.reset();
// div id
});
});
I think the problem comes from the line M.Modal.getInstance(modal).close();. It looks like modal is not defined. However, when I log it with console.log, the variable modal is existing.
You didn't initialize the modal,Just make the following change:
const modal = document.querySelector('#modal-signup');
var instance = M.Modal.init(modal);
M.Modal.getInstance(instance).close();
Also you haven`t use materialize css and script link :
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- Modal Structure -->