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 project is using the cocktail api to search for a specific ingredient (think gin or vodka) and then return all the drinks that contain the ingredient. I was able to get the results to display, but I wanted the thumbnail pic of the drink (included in the api as strDrinkThumb). When I try to get the pictures to display I get the follow error:
GET http://local/undefined 404 (Not Found)
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
let ingredients = document.getElementById('ingredients');
let searchTerm= document.getElementById('search-Bar');
let searchBtn = document.getElementById('searchBtn');
let drinkInfo = document.getElementById('drinkInfo');
let ingredientList = []
searchBtn.addEventListener("click", async (e) => {
const searchString = searchTerm.value.toLowerCase();
fetch(`https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${searchString}`)
.then((response) => response.json())
.then((filteredIngredients) => {
displayIngredient(filteredIngredients.drinks);
})
.catch((error) => {
});
});
function displayIngredient(drinkData){
const ingredients = [];
//maps over array and makes new array
drinkInfo.innerHTML = drinkData.map( ({strDrink}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${drinkData.strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');
drinkInfo.appendChild(drinkInfo);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cocktail App</title>
<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>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<input type="text" id="search-Bar" placeholder="Enter main ingredient..."/>
<button id="searchBtn">search</button>
</header>
<div class="drinkInfo" id="drinkInfo">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script type="text/javascript" src="./extrafile.js"></script>
</body>
</html>
In drinkData.map function you are only pulling strDrink value from the object, you need also get strDrinkThumb
Then you are trying get strDrinkThumb from drinkData which is an array, not an object.
Try this:
drinkInfo.innerHTML = drinkData.map( ({strDrink, strDrinkThumb}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');
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 am new in firebase I am making a simple profile with User information and I want to edit and store the data in the dp in the firebase
first I added the CDN this is my index.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>Level Up Elearning</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
<script src="/__/firebase/8.5.0/firebase-app.js"></script>
<script src="/__/firebase/8.5.0/firebase-analytics.js"></script>
<script src="/__/firebase/init.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.24.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.24.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
</body>
</html>
I tried all these scripts
and this is my firebase file
import firebase from "firebase/app";
var firebaseConfig = {...};
let fireDb = firebase.initializeApp(firebaseConfig);
export default fireDb.database().ref();
and this is where I call it
import React from "react";
import UserForm from "./UserForm";
import firebaseDb from "../firebase.js";
const UserProfile = () => {
const AddOrEdit = (obj) => {
firebaseDb.child("contacts").push(obj, (err) => {
if (err) {
console.log(err);
}
});
};
return (
<>
<div class="container py-4">
<div class="p-5 mb-4 bg-light rounded-3">
<div class="container-fluid py-5">
<h1 class="display-10 fw-bold">Profile Page</h1>
</div>
</div>
<div class="row align-items-md-stretch">
<div class="col-md-6">
<div class="h-100 p-5 text-white bg-dark rounded-3"></div>
</div>
<div class="col-md-6">
<div class="h-100 p-5 bg-light border rounded-3">
<UserForm AddOrEdit={AddOrEdit} /> // here I send the function as props to user form
</div>
</div>
</div>
</div>
</>
);
};
export default UserProfile;
this is a pic for the error
You're only importing firebase/app, which means the Realtime Database is not available in your code your.
to fix that, add:
import "firebase/database";
This then makes firebase.database() available as a side-effect.
I have two files created in LWC OSS app
first file at src/client/index.html and src/client/index.js
second file at src/client/index2.html and src/client/index2.js
I want to navigate to index2.html when clicked on the button in my-app (LWC component) which is appended using index.js
Am new to express js and node js. Please help!
Below is the code of the files,
index.html (File location: src/client/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My LWC App</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
<!-- Block zoom -->
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
<link rel="shortcut icon" href="./resources/favicon.ico" />
</head>
<body>
<div id="main"></div>
</body>
</html>
index.js (File location: src/client/index.js)
import { createElement } from 'lwc';
import MyApp from 'my/app';
const app = createElement('my-app', { is: MyApp });
// eslint-disable-next-line #lwc/lwc/no-document-query
document.querySelector('#main').appendChild(app);
app.html (File location: src/client/modules/my/app/app.html)
<template>
<!-- LWC sample component <my-greeting> -->
<div class="center greeting">
<!-- <my-greeting speed="slow"></my-greeting> -->
<my-greeting speed="medium"></my-greeting>
<!-- <my-greeting speed="fast"></my-greeting> -->
</div>
<div class="center">
<img src="./resources/lwc.png" />
</div>
<!-- Page code -->
<div class="center">
<div class="container">
<!-- prettier-ignore -->
<p class="info">
Edit <strong class="code">src/client/modules/my/app/app.html</strong>
<br />and save for live reload.
</p>
</div>
<div>
Learn LWC
<button onclick={redirect}>Click to redirect</button>
</div>
</div>
</template>
app.js (File location: src/client/modules/my/app/app.js)
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
redirect(){
//code for to navigate to index2.html
}
}
index2.html (File Location: src/client/index2.html)
<html lang="en">
<body>
<div id="main"></div>
</body>
</html>
index2.js (File Location: src/client/index2.js)
import { createElement } from 'lwc';
import MyNewApp from 'my/newApp';
const app = createElement('my-app', { is: MyNewApp });
// eslint-disable-next-line #lwc/lwc/no-document-query
document.querySelector('#main').appendChild(app);
7.newApp.html (File location: src/client/modules/my/newApp/newApp.html)
<template>
<h1> Redirected to index2 --> newApp </h1>
</template>
Please let me know if you need more information.
Thanks,
Navaprasad