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);
});
});
Related
I already check again on this code, but still couldn't figure it out why it won't work. So that I manage to make this web app using GitHub API.
but when I tried to search some data by their name, it turns out 'undefined' for everything that I was trying to find, like name, image, bio and etc.
My html code:
<html>
<head>
<title>Github Profile!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id="form">
<input type="text"
id="search"
placeholder="Search a User Here" />
</form>
<main id="main"></main>
<script src="script.js" defer></script>
</body>
</html>
Javascript:
const APIURL = 'https://api.github.com/users';
const main = document.getElementById('main');
const form = document.getElementById('form');
const search = document.getElementById('search');
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
function createUserCard(user) {
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}"
alt="${user.name}" />
</div>
<div>
<h2>${user.name}</h2>
<p>${user.bio}</p>
<ul>
<li>${user.followers}</li>
<li>${user.following}</li>
<li>${user.public_repos}</li>
</ul>
</div>
</div>
`;
main.innerHTML = cardHTML;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const user = search.value;
if (user) {
getUser(user);
search.value = "";
}
});
I don't know what actually went wrong here.
Looks like you were just using the wrong URL.
const APIURL = 'https://api.github.com/users'; // no end slash
async function getUser(user) {
const resp = await fetch(APIURL + user );
so what you're doing here is calling the URL
https://api.github.com/usersusername
so you just need to add a slash in the APIURL variable.
const APIURL = 'https://api.github.com/users/';
const main = document.getElementById('main');
const form = document.getElementById('form');
const search = document.getElementById('search');
async function getUser(user) {
const resp = await fetch(APIURL + user);
console.log(resp)
const respData = await resp.json();
console.log(respData)
createUserCard(respData);
}
function createUserCard(user) {
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}"
alt="${user.name}" />
</div>
<div>
<h2>${user.name}</h2>
<p>${user.bio}</p>
<ul>
<li>${user.followers}</li>
<li>${user.following}</li>
<li>${user.public_repos}</li>
</ul>
</div>
</div>
`;
main.innerHTML = cardHTML;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const user = search.value;
if (user) {
getUser(user);
search.value = "";
}
});
<html>
<head>
<title>Github Profile!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id="form">
<input type="text" id="search" placeholder="Search a User Here" />
</form>
<main id="main"></main>
<script src="script.js" defer></script>
</body>
</html>
Just add / after the users.
Your Code:
const APIURL = 'https://api.github.com/users';
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
Working Code:
const APIURL = 'https://api.github.com/users/';
async function getUser(user) {
const resp = await fetch(APIURL + user );
const respData = await resp.json();
createUserCard(respData);
}
This will get you the correct URL for the user
https://api.github.com/users/thesumitshrestha
I am training on the Hacker News API project and I wanted to do it my way, I fetched the API with the following urls and I put a toggle_button function but when I try to put the variable data in this function nothing is displayed I do not know what is the problem can someone guide me?
Here's 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">
<link rel="stylesheet" href="css/style.css">
<title>ClonerNews</title>
</head>
<body>
<h2>Welcome To <span>ClonerNews</span> !</h2>
<div id="main">
<button id="liveData" class="category" onclick="toggleButton('liveData');">Live Data</button>
<button id="topstories" class="category" onclick="toggleButton('topstories');">Top Stories</button>
<button id="stories" class="category" onclick="toggleButton('stories');">Stories</button>
<button id="jobs" class="category" onclick="toggleButton('jobs');">Jobs</button>
<button id="polls" class="category" onclick="toggleButton('polls');">Polls</button>
</div>
<div id="result"></div>
<span id="span_txt" style="color: aliceblue;"></span>
</body>
<script src="script.js"></script>
</html>
And here's my script.js
//url of news api
var topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json";
//url of particular news item
var newItemUrl = "https://hacker-news.firebaseio.com/v0/item/";
let result = document.getElementById("result"); seront affichées.
//fetch data
const fetchData = (url) => {
return new Promise((resolve, reject) => {
fetch(url)
.then((res) => res.json())
.then((data) => resolve(data))
.catch((err) => reject(err));
});
};
//show data
const showData = async () => {
var data = await fetchData(topStoriesUrl);
console.log(data);
data.map(async (d) => {
let newsData = await fetchData(`${newItemUrl}${d}.
json`);
console.log(newsData);
});
};
showData();
const liveData = getElementById("liveData");
const stories = getElementById("stories");
const jobs = getElementById("jobs");
const polls = getElementById("polls");
function toggleButton() {
var span = document.getElementById("span_txt");
if(span.innerHTML != "") {
span.innerHTML = "";
} else {
span.innerHTML = data
}
}
Could anyone explain to me why I cannot update my input value after clicking my submit button? My goal is to write a number, click the submit button and find the Pokémon with that number.
<!DOCTYPE html>
<html lang="en">
<head>
<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>Document</title>
</head>
<body>
<div class="pokemon"></div>
<button id="btn" onclick="testFunc(inputValue)">SUBMIT</button>
<input type="text" value="" id="myInput">
<script>
const btn = document.getElementById("btn");
const input = document.getElementById("myInput");
let inputValue = input.value;
const testFunc = function(a) {
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: a,
}
const { url, type, id } = apiData
const apiUrl = `${url}${type}/${id}`
fetch(apiUrl)
.then((data) => {
if (data.ok) {
return data.json()
}
throw new Error('Response not ok.');
})
.then(pokemon => generateHtml(pokemon))
.catch(error => console.error('Error:', error))
const generateHtml = (data) => {
console.log(data)
const html = `
<div class="name">${data.name}</div>
<img src=${data.sprites.front_default}>
<div class="details">
<span>Height: ${data.height}</span>
<span>Weight: ${data.weight}</span>
</div>
`
const pokemonDiv = document.querySelector('.pokemon')
pokemonDiv.innerHTML = html
}
}
</script>
</body>
</html>
I will be grateful for any advice.
Best regards
You need to move the inputValue retrieval inside the testFunc function.
const testFunc = function() {
let inputValue = input.value;
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: inputValue,
}
The button's onclick only knows about itself, it cannot reference input.
const btn = document.getElementById("btn");
const input = document.getElementById("myInput");
const testFunc = function() {
let inputValue = input.value;
const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: inputValue,
}
const { url, type, id } = apiData
const apiUrl = `${url}${type}/${id}`
fetch(apiUrl)
.then((data) => {
if (data.ok) {
return data.json()
}
throw new Error('Response not ok.');
})
.then(pokemon => generateHtml(pokemon))
.catch(error => console.error('Error:', error))
const generateHtml = (data) => {
//console.log(data) <-- Slows down the result
const html = `
<div class="name">${data.name}</div>
<img src=${data.sprites.front_default}>
<div class="details">
<span>Height: ${data.height}</span>
<span>Weight: ${data.weight}</span>
</div>
`
const pokemonDiv = document.querySelector('.pokemon')
pokemonDiv.innerHTML = html
}
}
<div class="pokemon"></div>
<button id="btn" onclick="testFunc()">SUBMIT</button>
<input type="text" value="25" id="myInput"> <!-- Default to Pikachu -->
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.
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