I have written a code to enter and save data to firebase. The data is saved perfectly, but now i want to display the same data using javascript on my html page. How do i do it? (P.S I have referred the issue in many places but none of them work for my document. For reference i have put them inside comments in the js file) Following is the javascript file and HTML for reference.
main.js
// Initialize Firebase
var config = {
apiKey: "AIzaSyC7HkjUoZe0Bj4xAd3up9rMXoMWay8MCpE",
authDomain: "contactform-9133a.firebaseapp.com",
databaseURL: "https://contactform-9133a.firebaseio.com",
projectId: "contactform-9133a",
storageBucket: "contactform-9133a.appspot.com",
messagingSenderId: "950534208323"
};
firebase.initializeApp(config);
//ref msg collection (collections are tables)
var messagesRef = firebase.database().ref('messages');
// var ref = firebase.database().ref();
document.getElementById('contactform').addEventListener('submit',
submitForm);
/*var list = document.getElementById('namelist');
var listRef = friebase.database().ref().child('name');
listRef.on('value', function(datasnapshot) {
list.innerHTML = datasnapshot.val();
});*/
/*ref.on('value', function(snapshot) {
console.log(snapshot.val());
});*/
//submit form to database
function submitForm(e) {
e.preventDefault();
//get values
var name = getInputVal('name');
var address = getInputVal('address');
var email = getInputVal('email');
var phone = getInputVal('phone');
var password = getInputVal('password');
/*function gotData(name, address, email, phone, password) {
var n = name.val();
console.log(n);
//var keys = Object.keys(messages);
// console.log(keys);
}*/
saveMessage(name, address, email, phone, password);
//show alert
document.querySelector('.alert').style.display = 'block';
//hide alert after three secs
setTimeout(function() {
document.querySelector('.alert').style.display = 'none';
}, 3000);
document.getElementById('contactform').reset();
}
//function to get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
function saveMessage(name, address, email, phone, password) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
address: address,
email: email,
phone: phone,
password: password
});
//var hot = newMessageRef.val();
//var keys = Object.keys(hot);
/* for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var name1 = hot[k].name;
console.log(name1);
//var li = document.createElement('li', name);
//li.parent('namelist');
}*/
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Comaptible" content="ie=edge">
<title>Medi Aid</title>
<link href="https://maxcdn.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
integrity="sha384-
wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<h1 class="brand"><span>Medi Aid</span></h1>
<div class="wrapper animated bounceInLeft">
<div class="our-info">
<h3>Medi Aid</h3>
<ul>
<li><i class="fa fa-road"></i> SRM IST</li>
<li><i class="fa fa-phone"></i> Ph-no:000 000</li>
<li><i class="fa fa-envelope"></i> Email</li>
</ul>
</div>
<div class="contact">
<h3>Email Us</h3>
<!--To do validation -->
<div class="alert">You have been signed up</div>
<form id="contactform">
<p>
<label>Name</label>
<input type="text" name="name" id="name" required>
</p>
<p>
<label>Address</label>
<input type="text" name="address" id="address" required>
</p>
<p>
<label>Email Address</label>
<input type="email" name="email" id="email" required>
</p>
<p>
<label>Phone Number</label>
<input type="text" name="phone" id="phone">
</p>
<p class="full">
<label>Password</label>
<input type="password" name="password" id="password"
required>
</p>
<p class="full">
<button type="submit">Submit</button>
</p>
</form>
</div>
</div>
</div>
<script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js">
</script>
<script src="main.js"></script>
</body>
</html>
I also tried the below stuff, but it's still not working:
main.js(contd.)
messagesRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var name_val = childSnapshot.val().name;
console.log(name_val);
// $("#namelist").append(name_val);
$("#namelist").append("<p>" + name_val + "</p>");
});
});
Try this.
ref.child('your-node').child('your-node').once('value').then(function(snap) {
if(snap.val()){
//do your thing here.
console.log(snap.val());
}
}, function(error) {
// The Promise was rejected.
console.log('Error: ',error);
});
Related
I'm making a code where the user enters information and it stores it in an object, but when I check if the object is saved by alerting one of its values it says there is no such object.
here is my code.
let users = {};
function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.subs = 0,
this.videos = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
users[name] = new user(username, name);
};
let savefile = () => {
var channame = string(document.getElementById('channame'));
var name = string(document.getElementById('name'));
var email = string(document.getElementById('email'));
newuser(name,email,channame);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>youtube ripoff</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br> <br><br><br><br><br>
<form action="">
<label for="username">Channel Name: </label>
<input type="text" id="channame" name="channelname"><br>
Real Name
<input type="text" id="name" name="name"><br>
Email
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit" onmousedown="newuser('name1','name#gmail.com','channelname1');">
<br><br><br><br>
<input type="button" value="Load Channels" id="seech" name="seechannels" onmousedown="alert(users['name1'].listuser());"><br>
</form>
<script src="script.js">
function fun(){
window.alert("starting program...")
//other code
}
</script>
</body>
</html>
Is there some sort of error that I'm not seeing?
After click on submit button in form with action="" page is reload and all data is lost. Pleas use:
<form action="javascript:void(0)">
instead of
<form action="">
This prevent page reload.
I have a login system that loops through an array of objects to fetch and compare username and password entered by the user in the login page. I have issued an if statement to check if user credentials are correct. The problem am having is that the system shows the else statement even when the if statement has passed or the user credentials are correct.
Please see the full demo in the link below;
https://jsfiddle.net/dej5sr9z/
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<meta name="generator" content="Ayub Technologies">
<meta name="author" content="Verai Bosobori" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="description" content="">
<title>Lycan CREATIONS | Home</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<section>
<div class="form_div">
<h2>Login</h2>
<div style="text-align:left; color:red; font-weight:bold;" id="error"></div>
<div style="text-align:left; color:green; font-weight:bold;" id="success"></div>
<br>
<form action="#">
<div class="form_input">
<label for="">Username</label>
<input type="text" id="username" placeholder="">
</div> <br>
<div class="form_input">
<label for="">Password</label>
<input type="password" id="passwd" placeholder="">
</div>
<div class="form_input">
<p style="text-align:left; color:blue;">Forgot Password?</p>
</div>
<div class="form_submit">
<button type="submit" onclick="getInfo()">Submit</button>
</div>
</form>
</div>
</section>
</body>
</html>
Beolow is the JavaCript Code
var objPeople =[
{
username: "verai",
passwd: "lycan"
},
{
username: "ayub",
passwd: "metah"
},
{
username: "chris",
passwd: "forever"
}
]
function getInfo(){
var username = document.getElementById("username").value;
var passwd = document.getElementById("passwd").value;
var error = document.getElementById("error").innerHTML;
if (username != '' || passwd != ''){
for(i = 0; i < objPeople.length; i++){
if(username == objPeople[i].username && passwd == objPeople[i].passwd){
document.getElementById("success").innerHTML = "Hello " + username + "!! You are successfully logged in!!!";
console.log(username + " is logged in!!!");
setTimeout(function(){
document.getElementById("success").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},5000);
}else{
document.getElementById("error").innerHTML = " Incorrect Username or Password. Please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
}else{
// console.log("Your username is " + username + " and your password is " + passwd );
document.getElementById("error").innerHTML = "All fields required, please try again!";
setTimeout(function(){
document.getElementById("error").innerHTML = "";
document.getElementById("username").value = "";
document.getElementById("passwd").value = "";
},2000);
}
}
I will appreciate if someone points out what am not doing right, thanks.
Assuming a correct combination has been entered, the for-loop goes into the if-part once for the matching user, but also it goes into the else-part for all other non-matching users. There is nothing in place to prevent that from happening.
You need to determine who is the one matching person if any, and then proceed with that result (which is either a user object, or undefined).
You can do so with find, using code like this:
var matchingUser = objPeople.find(p => username === p.username && passwd === p.passwd);
if (matchingUser) {
// ...
} else {
// ...
}
Side note - I used the "triple equal sign", which does an exact comparison between objects without any type conversions that could get in the way.
I do not know how to delete the specific record when I click the img on the right
I want it to work like that:
Also I put an img for delete the specific record but I do not know how to add an event listener on img in the JS to delete the row and the record. Also, when I insert data in the DB I add the UID of the specific object for the delete purposes.
HTML code
<html>
<head>
<title>Fall-App Admin Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK rel="stylesheet" href="style.css" type="text/css" media="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
</head>
<body>
<div class="cabecera">
</div>
<div class="cuerpo">
<div class="botones">
<table style="background-color:grey;height:100%; width:99%" border="10" id="logout">
<tr><td>Επεξεργασία Κοινωνικών Υπηρεσιών</td></tr>
<tr><td>Αποσύνδεση</td></tr>
</table>
</div>
<div class="welcome">
<div class="container">
<!--<form>
<input class="input" type="text" id="searchTxt" placeholder="Αναζήτηση για ...">
<input class="submit" type="submit" id="searchBtn" value="Εύρεση">
</form>-->
<input type="text" placeholder="Επιβεβαίωση Κωδικού" name="rePsw" id="rePswReg" required>
<button type="submit" id="searchBtn">Εγγραφή</button>
<table class="searchTable" style="width:100%">
<thead>
<tr>
<td>Name Of Service</td>
<td>Address</td>
<td>Postal</td>
<td>City</td>
<td>Phone</td>
<td>Delete</td>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</div>
<form id="submitForm">
Name Of Service:<br>
<input type="text" name="name" id="nameDB"><br>
Address:<br>
<input type="text" name="address" id="addressDB">
Postal:<br>
<input type="text" name="postal" id="postalDB">
City:<br>
<input type="text" name="city" id="cityDB">
Phone:<br>
<input type="text" name="phone" id="phoneDB">
<button type="submit" id="btnInsert">Inster</button>
</form>
<script src="registered.js"></script>
</div>
</div>
<div class="pie">
</div>
</body>
</html>
JS code
(function() {
//initialize Firebase
var config = {
};
firebase.initializeApp(config);
const searchBtn = document.getElementById('searchBtn');
//const searchTxt = document.getElementById('searchTxt');
var messagesRef2 = firebase.database().ref().child('socialServices');
var counter=-1;
//bring all to the table
var messagesRef2 = firebase.database().ref().child('socialServices');
messagesRef2.on("child_added", snap => {
counter++;
var name=snap.child("name").val();
var address=snap.child("address").val();
var postal=snap.child("postal").val();
var city=snap.child("city").val();
var phone=snap.child("phone").val();
$("#tableBody").append("<tr><td>" + name + "</td><td>" + address + "</td><td>" +
postal + "</td><td>" + city + "</td><td>" + phone + "</td><td>" + "<img src='http://icons.iconarchive.com/icons/hopstarter/button/16/Button-Close-icon.png' id='Img'>" + "</td></tr>");
});
//regerence messages collection
var messagesRef = firebase.database().ref('socialServices');
//listen for form submit
document.getElementById('submitForm').addEventListener('submit', submitForm);
//submit form
function submitForm(e){
e.preventDefault();
//get values
var name=getInputVal('nameDB');
var address=getInputVal('addressDB');
var postal=getInputVal('postalDB');
var city=getInputVal('cityDB');
var phone=getInputVal('phoneDB');
//save message
saveMessage(name, address, postal, city, phone);
}
//function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
//save message to firebase
function saveMessage(name, address, postal, city, phone){
var newMessageRef = messagesRef.push();
newMessageRef.set({
id: newMessageRef.key,
name: name,
address: address,
postal: postal,
city: city,
phone: phone
});
}
}());
I have a table that gets populated with data from Firebase. Each tr shows that data. I have dynamically created a form that gets appended to each tr, the problem is that it is not showing and I can't figure out why. I inspected each tr with the dev tools and it shows that the form with the input is indeed there but for some reason it is not visible, why? Here is my html:
const animalList = document.querySelector('#animal-list');
const form = document.querySelector('#add-animals');
function renderAnimals(doc) {
let tr = document.createElement('tr');
let deleteButton = document.createElement('button');
let name = document.createElement('div');
let species = document.createElement('div');
let age = document.createElement('div');
let last_fed = document.createElement('div');
let last_shed = document.createElement('div');
let diet = document.createElement('div');
let basking_area_temp = document.createElement('div');
let cold_part_temp = document.createElement('div');
let humidity = document.createElement('div');
let additional_info = document.createElement('div');
// The form that does not become visible
let form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "default.aspx");
form.setAttribute("target", "_blank");
let inputField = document.createElement("input");
inputField.setAttribute("name", "firtname");
inputField.setAttribute("value","product1,product2" );
inputField.setAttribute("type", "text");
form.setAttribute("class", "f")
form.appendChild(inputField);
tr.setAttribute('data-id', doc.id);
name.textContent = `name: ${doc.data().name}`
deleteButton.textContent = 'Delete';
deleteButton.setAttribute('class','btn btn-danger');
species.textContent = `species: ${doc.data().species}`
age.textContent = `age: ${doc.data().age}`
last_fed.textContent = `last fed: ${doc.data().last_fed}`;
last_shed.textContent = `last shed: ${doc.data().last_shed}`;
diet.textContent = `diet: ${doc.data().diet}`;
basking_area_temp.textContent =`basking area temp: ${ doc.data().basking_area_temp}`;
cold_part_temp.textContent = `cold part temp: ${doc.data().cold_part_temp}`;
humidity.textContent = `humidity: ${doc.data().humidity}`;
additional_info.textContent = `additional info: ${doc.data().additional_info}`;
tr.appendChild(species);
tr.append(name);
tr.append(age);
tr.append(last_fed);
tr.append(last_shed);
tr.append(diet);
tr.append(basking_area_temp);
tr.append(cold_part_temp);
tr.append(humidity);
tr.append(additional_info);
tr.append(deleteButton);
tr.append(form);
animalList.appendChild(tr);
//deleting data
deleteButton.addEventListener('click', (event) => {
event.stopPropagation();
let id = event.target.parentElement.getAttribute('data-id');
db.collection('animals').doc(id).delete();
})
}
// getting data from the back end
db.collection('animals').onSnapshot(snapshot => {
let changes = snapshot.docChanges();
changes.forEach(change => {
if(change.type == 'added') {
renderAnimals(change.doc);
} else if (change.type == 'removed') {
let li = animalList.querySelector('[data-id=' + change.doc.id + ']');
animalList.removeChild(li);
}
})
})
// adding data
form.addEventListener('submit', (event) => {
event.preventDefault();
db.collection('animals').add({
species: form.species.value,
name: form.name.value,
age: form.age.value,
last_fed: document.querySelector('#last-fed').value,
last_shed: document.querySelector('#last-shed').value,
diet: form.diet.value,
basking_area_temp: document.querySelector('#basking-area-temperature').value,
cold_part_temp: document.querySelector('#cold-temperature').value,
humidity: form.humidity.value,
additional_info: document.querySelector('#additional-info').value
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Repti Care</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://www.gstatic.com/firebasejs/5.5.7/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.5/firebase-firestore.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="./css/main.css">
</head>
<body>
<div class="jumbotron">
<div class="placeholder"></div>
</div>
<div class="container">
<h2>Add a new Animal</h2>
<form class="form-group" id="add-animals">
Species: <input type="text" id="species" class="form-control">
Name: <input type="text" id="name" class="form-control" >
Age: <input type="text" id="age" class="form-control">
Last Fed: <input type="date" id="last-fed" class="form-control">
Last Shed: <input type="date" id="last-shed" class="form-control">
Diet: <input type="text" id="diet" class="form-control">
Basking area temperature: <input type="text" id="basking-area-temperature" class="form-control">
Cold part temperature: <input type="text" id="cold-temperature" class="form-control">
Humidity: <input type="text" id="humidity" class="form-control">
Addition Info: <textarea class="form-control" id="additional-info"></textarea>
<button id="btnCreate" class="btn btn-primary">Create</button>
</form>
<h3>View Current Animals</h3>
<table id="animal-list">
<th>Animals</th>
</table>
</div>
</div>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBSuC8nqJzLe7d5jKS-_nE15kaI9Y6NIfI",
authDomain: "repti-care-32176.firebaseapp.com",
databaseURL: "https://repti-care-32176.firebaseio.com",
projectId: "repti-care-32176",
storageBucket: "repti-care-32176.appspot.com",
messagingSenderId: "632910932105"
};
firebase.initializeApp(config);
const db = firebase.firestore();
db.settings({ timestampsInSnapshots: true });
</script>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="./scripts/main.js"></script>
</body>
</html>
The problem here is that you're appending elements (name, age, etc.) to a tr element. You need to add a td element inside your tr then append to the td.
Solution:
After let tr = document.createElement("tr"); add let td = document.createElement("td");.
Change tr to td in all 12 lines from tr.appendChild(species); to tr.append(form);.
After td.append(form); add tr.appendChild(td);
https://codepen.io/rockysims/pen/VVQmYB
I am trying to make a registration and login form using javascript, it's like, once a user registers the data is stored in an array and then that data is used to authenticate the user and display the user details on the page, after logging in the alert is not popping, Please help! thanks in advance.
Following is my register.html and controller.js-
register.html
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<meta charset=utf-8 />
<title>Register</title>
<style>
article, aside, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
</style>
</head>
<body>
<form>
<h1>Please enter data</h1> FirstName:
<input id="firstname" type="text" placeholder="FirstName" />
<br> LastName :
<input id="lastname" type="text" placeholder="LastName" />
<br> Email ID :
<input id="email" type="text" placeholder="Email" />
<br> UserName :
<input id="username" type="text" placeholder="UserName" />
<br> Password :
<input id="password" type="password" placeholder="Password" />
<br>
<input type="button" value="Register" onclick="insert()" />
</form>
<!--Login form-->
<div id="demo" style="display:none">
<div class="container">
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username" />
<label>Password :</label>
<input type="password" name="password" id="password" />
<input type="button" value="Login" id="submit" onclick="validate()" />
</form>
</div>
</div>
<br>
<button type="button" onclick="document.getElementById('demo').style.display='block'">Login!</button>
<div id="display"></div>
<script src="D:/Xperience/js/controller.js">
</script>
</body>
</html>
controller.js
var users = [];
localStorage.setItem("keyforusers", JSON.stringify(users));
var idInput = (users.length) + 1;
var firstnameInput = document.getElementById("firstname");
var lastnameInput = document.getElementById("lastname");
var emailInput = document.getElementById("email");
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");
var messageBox = document.getElementById("display");
function userdetails(id, firstname, lastname, email, username, password) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.username = username;
this.password = password;
}
function insert() {
var user = new userdetails(idInput.value, firstnameInput.value, lastnameInput.value, emailInput.value, usernameInput.value, passwordInput.value);
users.push(user);
//Clear the fields
firstnameInput.value = "";
lastnameInput.value = "";
emailInput.value = "";
usernameInput.value = "";
passwordInput.value = "";
}
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
ulen = users.length;
for (i = 0; i < ulen; i++) {
if (username == users[i].username && password == users[i].password) {
alert("Logged in successfully");
}
}
username.value = "";
password.value = "";
}