I am trying to get and show my data from the firebase database to the HTML page in a table form, but no output showing. I attached a screenshot of my database below. I have been trying for like days and can't solve it. Can someone help me to point out what my problem is? For security purposes, I erased the details of my firebase configuration there.
<body>
<table>
<thead>
<th>Sno</th>
<th>First Name</th>
<th>Second Name</th>
<th>Email</th>
<th>LastLogin</th>
<th>Confirm Password</th>
</thead>
<tbody id="tbody1">
</tbody>
</table>
<script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-database.js"></script>
<script id="MainScript">
var firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(firebaseConfig);
//---------------------GET ALL DATA-------------------------------//
function SelectAllData(){
firebase.database().ref('admins').once('value',
function(AllRecords){
AllRecords.forEach(
function(CurrentRecord){
var firstName = CurrentRecord.val().first_name;
var secondName = CurrentRecord.val().second_name;
var email= CurrentRecord.val().email;
var lastLogin = CurrentRecord.val().last_login;
var conpassword = CurrentRecord.val().confirm_password;
AddItemsToTable(firstName,secondName,email,lastLogin,conpassword);
}
);
});
}
window.onload = SelectAllData;
//------------------filling the table-------------------//
var stdNo = 0;
function AddItemsToTable(firstName,secondName,email,lastLogin,conpassword){
var tbody = document.getElementById('tbody1');
var trow = document.createElementById('tr');
var td1 = document.createElementById('td');
var td2 = document.createElementById('td');
var td3 = document.createElementById('td');
var td4 = document.createElementById('td');
var td5 = document.createElementById('td');
var td6 = document.createElementById('td');
td1.innerHTML= ++stdNo;
td2.innerHTML= firstName;
td3.innerHTML= secondName;
td4.innerHTML= email;
td5.innerHTML= lastLogin;
td6.innerHTML= conpassword;
trow.appendChild(td1);
trow.appendChild(td2);
trow.appendChild(td3);
trow.appendChild(td4);
trow.appendChild(td5);
trow.appendChild(td6);
tbody.appendChild(trow);
}
</script>
</body>
The way I pushed the data into database
// Set up our register function
function register () {
// Get all our input fields
email = document.getElementById('email').value
password = document.getElementById('password').value
first_name = document.getElementById('first_name').value
second_name = document.getElementById('second_name').value
confirm_password = document.getElementById('confirm_password').value
// Validate input fields
if (validate_email(email) == false || validate_password(password) == false) {
alert('Email or Password is Outta Line!!')
return
// Don't continue running the code
}
if (validate_field(first_name) == false || validate_field(second_name) == false || validate_field(confirm_password) == false) {
alert('One or More Extra Fields is Outta Line!!')
return
}
// Move on with Auth
auth.createUserWithEmailAndPassword(email, password)
.then(function() {
// Declare admin variable
var user = auth.currentUser
// Add this admin to Firebase Database
var database_ref = database.ref()
// Create Admin data
var user_data = {
email : email,
first_name : first_name,
second_name : second_name,
confirm_password : confirm_password,
last_login : Date.now()
}
// Push to Firebase Database
database_ref.child('admins/' + user.uid).set(user_data)
// DOne
alert('Admin Account Created!!')
window.location = "login.html";
})
.catch(function(error) {
// Firebase will use this to alert of its errors
var error_code = error.code
var error_message = error.message
alert(error_message)
});
}
You misspelled the method to create new elements. Replace document.createElementById (does not exist) with document.createElement and your page should work fine. To avoid such headaches in the future, I suggest using a code editor with code completion, e.g. Visual Studio Code (free).
Related
I do not have much experience with programming and am looking for help figuring out why city and state webform fields are not getting populated by the google location api script when a form submits. We have about a 30% failure rate and don't appear to be hitting any api call limits and this is not due to invalid postal codes. Can't figure out what the issue is.
Background:
We have forms on our sites with these visible fields:
Name
Email
Postal Code
Country (picklist)
And these hidden fields (to be populated by a call from a script on the page):
City
State
The basic process we are looking for is:
When the user enters into the form a Postal Code length greater than or equal to 5 AND Country is not empty THEN call to google's location api and populate the forms hidden fields with City and State.
Here are the scripts we are using:
Script placed in Head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
Script place before the body end tag:
<script type='text/javascript' >
$(document).ready(function() {
// Get city/state only if country has been selected and postal code is at least
// 5 characters long
$('#PostalCode,#Country').change(function() {
var postalCode = $('#PostalCode').val();
var countryCode = $('#Country option:selected').val();
if (postalCode.length >= 5 && countryCode !== '') {
getResponse(postalCode);
}
});
})
function getResponse(postalCode) {
var apiKey = 'OurAPIkeyIshere';
var baseUrl = `https://maps.googleapis.com/maps/api/geocode/json?&key=`;
var countryCode = $('#Country option:selected').val();
var componentFilter = `&components=country:${ countryCode }|postal_code:${ postalCode }&`;
var date = new Date();
var dateTime = `&_=${ date.getTime() }`;
var url = baseUrl + apiKey + componentFilter + dateTime;
$.support.cors = true;
$.ajaxSetup({ cache: false });
$.getJSON(url, function(response) {
var getStatus = response.status;
if (getStatus === 'OK') {
getCityState(response.results[0].address_components);
}
});
}
function getCityState(addressComponents) {
var city, state, nbhd, subLoc = '';
var hasCity, hasPostalTown, hasSubLoc = false;
$.each(addressComponents, function(index, addressComponent) {
var types = addressComponent.types;
$.each(types, function(index, type) {
switch(type) {
case 'postal_town':
postalTown = addressComponent.long_name;
hasPostalTown = true;
break;
case 'locality':
city = addressComponent.long_name;
hasCity = true;
break;
case 'sublocality':
subLoc = addressComponent.long_name;
hasSubLoc = true;
break;
case 'neighborhood':
nbhd = addressComponent.long_name;
break;
case 'administrative_area_level_1':
state = addressComponent.short_name;
break;
}
});
});
// set the city
if(hasPostalTown) {
$('#City').val(postalTown);
} else if(hasCity) {
$('#City').val(city);
} else if(hasSubLoc) {
$('#City').val(subLoc);
} else {
$('#City').val(nbhd);
}
// set the state
$('#State').val(state);
// reset flags
hasCity = false;
hasPostalCode = false;
hasSubLoc = false;
}
</script>
Actually, I deployed a website through Firebase and it was successful. Then there was nothing in the website .the website is www.novusorg.com The website is just about the organization. But now I added a registration form for the website. The registration form in HTML with ids is connected with JavaScript. And I deployed it again. But now when I try to open the website it says insecure connection. Please help me with the error.
EMERGENCY
THANK YOU IN ADVANCE
website: www.novusorg.com
var config = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "novuxxxxxxxxxxxx.firebaseapp.com",
databaseURL: "https://novusxxxxxxxxxxxxx.firebaseio.com",
projectId: "novxxxxxxxxxxxxxx",
storageBucket: "",
messagingSenderId: "xxxxxxxxxxxx"
};
firebase.initializeApp(config);
//reference messages collection
var messagesRef = firebase.database().ref('messages');
document.getElementById('registrationform1').addEventListener('submit',submitform);
function submitform(e) {
e.preventDefault();
var regname = getInputVal('regname');
var regmail = getInputVal('regmail');
var regregnum = getInputVal('regregnum');
var regnumber = getInputVal('regnumber');
var regcourse = getInputVal('regcourse');
var regreason = getInputVal('regreason');
var regfd= getInputVal('regfd');
var regbd = getInputVal('regbd');
var regad = getInputVal('regad');
var regiod = getInputVal('regiod');
var reguxd = getInputVal('reguxd');
var regpty = getInputVal('regpty');
var reggfd = getInputVal('reggfd');
var regved = getInputVal('regved');
var regfa = getInputVal('regfa');
var regcw = getInputVal('regcw');
var regmt = getInputVal('regmt');
var regem = getInputVal('regem');
saveMessage(regname,regmail,regregnum,regnumber,regcourse,regreason,regfd,regbd,regad,regiod,reguxd,regpty,reggfd,regved,regfa,regcw,regmt,regem);
document.querySelector('.regalert').style.display='block';
setTimeout(function(){
document.querySelector('.regalert').style.display='none';
},3000);
document.getElementById('registrationform1').reset();
}
function getInputVal(id) {
return document.getElementById(id).value;
}
function saveMessage(regname,regmail,regregnum,regnumber,regcourse,regreason,regfd,regbd
, regad,regiod,reguxd,regpty,reggfd,regved,regfa,regcw,regmt,regem) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
regname:regname,
regmail:regmail,
regregnum:regregnum,
regnumber:regnumber,
regcourse:regcourse,
regreason:regreason,
regfd:regfd,
regbd:regbd,
regad:regad,
regiod:regiod,
reguxd:reguxd,
regpty:regpty,
reggfd:reggfd,
regved:regved,
regfa:regfa,
regcw:regcw,
regmt:regmt,
regem:regem
});
}
I don't see your landing page on the website, I instead see a Google Docs page.
Above is the db structure and below is the code to retrieve the data from firebase database, I am unable to get the data from my db.I need help in retrieving the data from my firebase db.I have attached the database image for the view of my db.
function check(userId,snapcity){
var rootRef=firebase.database().ref().child('users');
rootRef.on('child_added', function(snap){
if(snap.child("userId").val()==userId){
snapcity=snap.child("city").val();
}
});
console.log(snapcity);
console.log(ajaxData.geoplugin_city);
if(snapcity){
if(snapcity!=ajaxData.geoplugin_city){
logout();
alert("you can't login because previously you were logged from "+snapcity );
}
}
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
userId=user.uid;
//alert(userId);
var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();
datetime=n+" "+time;
snapcity="";
check(userId,snapcity);
var database = firebase.database();
writeUserData(userId,ajaxData.geoplugin_request,ajaxData.geoplugin_city,datetime);
document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var user = firebase.auth().currentUser;
if(user != null){
var email_id = user.email;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
console.log('data');
console.log(ajaxData);
html="<p>ip: "+ajaxData.geoplugin_request+"</p><p>Country Code: +44</p><p>Country: "+ajaxData.geoplugin_countryName+"</p><p>Country Abbrevation: "+ajaxData.geoplugin_countryCode+"</p><p>Region Code: "+ajaxData.geoplugin_regionCode+"</p><p>Region Name: "+ajaxData.geoplugin_regionName+"</p><p>City: "+ajaxData.geoplugin_city+"</p><p>Time Zone: "+ajaxData.geoplugin_timezone+"</p><p>Latitude: "+ajaxData.geoplugin_latitude+"</p><p>Longitude: "+ajaxData.geoplugin_longitude+"</p><p>Last Login: "+datetime+"</p>";
$('#data').html(html);
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
[1]: https://i.stack.imgur.com/JVeRD.jpg
This:
rootRef.on('child_added', function(snap){
if(snap.child("userId").val()==userId){
snapcity=snap.child("city").val();
}
});
Can be replaces by:
rootRef.child(userId).once('value', function(snap){
snapcity = snap.child("city").val();
});
Next you need to move all code that needs snapcity into the callback function. So:
rootRef.child(userId).once('value', function(snap){
snapcity = snap.child("city").val();
console.log(snapcity, ajaxData.geoplugin_city);
if(snapcity){
if(snapcity!=ajaxData.geoplugin_city){
logout();
alert("you can't login because previously you were logged from: "+snapcity );
}
}
});
So I am new to web development and Firebase as well. I have been trying to build a multi page web app in simple javascript and firebase. App looks good and works for most of the part. Yet it is really of no use as I am having following issue :
When I sign in through googleAuthProvider (on my index.html page), I am taken to another page which is main.html . Now til here is fine. But once the main.html is loaded, it goes into a loop of continuous refreshing.
My rationale behind this is, that somehow Firebase is trying to re-authenticate the page on loading. And so the loop happens. But why, this I am not able to debug.
I have looked over almost everything I could find on internet but no where I could find a solution which is for simple javascript based multi page web app with firebase.
Here's a link to my app if anyone is interested and kind enough to have a look.
Chatbot
Also, here is my javascript code too.
var config = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXX",
storageBucket: "XXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXX"
};
firebase.initializeApp(config);
//===============================================================================================
$("document").ready(function(){
const signinGoogle = document.getElementById("googleAuth");
const signOut = document.getElementById("signout");
const sendMsg = document.getElementById("send");
const messageBox = document.getElementById("chatBox");
const displayNAME = document.getElementById("dipslayName");
const storageRef = firebase.storage().ref();
var currentUser;
var name;
var photoUrl;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initApp();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signinGoogle){
googleAuth.addEventListener('click', e=>{
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider()).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var tokenGoogle = result.credential.accessToken;
// The signed-in user info.
var userGoogle = result.user;
// ...Below line to be rmeooved if not working expectedly.
// var user = firebase.auth().currentUser;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signOut){
signout.addEventListener('click', e=>{
if(confirm("Do you wish to leave?")){
promise = firebase.auth().signOut().then(function(){
window.location = "index.html";
});
promise.catch(e =>
console.log(e.message))
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function initApp(){
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
$("document").ready(function(){
currentUser = firebase.auth().currentUser;
name = currentUser.displayName;
photoUrl = currentUser.photoURL ;
console.log("Current user's name is : "+name);
console.log("Current user's photoUrl is : "+photoUrl);
displayNAME.innerHTML = "Hi "+name;
//+++++++++++Retrieving Msgs++++++++++++++++++++++++++++++++
var i=1;
var firebaseRetrieveRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseRetrieveRef.on("child_added", snap =>{
var retrievedMsg = snap.val();
console.log("retrieved msgs is : "+retrievedMsg);
$("#taskList").append("<li id='list"+i+"'><div style='width:100%'><img src='"+photoUrl+"'style='width:10px;height:10px;border-radius:5px;'/><label>"+name+"</label></div><div style='width:100%'><p>"+retrievedMsg+"</p></div></li>");
i++;
});
//+++++++++++Storing Msgs++++++++++++++++++++++++++++++++
$("#send").on("click", function(){
var newMessage=messageBox.value;
if(newMessage==""){
alert("Empty Message doesn't make any sense, does it?? ");
}
else{
var firebaseStoreRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseStoreRef.push().set(newMessage);
messageBox.value="";
}
});
//+++++++++++Clearing/deleting all tasks++++++++++++++++++++++++
$("#clear").on("click", function(){
var firebaseDeleteRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseDeleteRef.remove();
$( ".scrolls" ).empty();
});
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
}
else
{
console.log(user+" is not logged in");
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
You keep redirecting to main.html.
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
You keep redirecting to main.html whenever you determine the user is signed in. Make sure on main.html, you are not using the same logic and redirecting again.
I am trying to use local storage to make a basic registration and login screen.
I have managed to get all the basics running but I can't get the fields to save to the local storage to them pull for the login process. I do not believe the HTML is wrong but the Javascript.
Here is the JS:
function save() {
var inputUserName = document.getElementById('regusername');
var inputPassWord = document.getElementById('regpassword');
var inputEmail = document.getElementById('regemail');
localStorage.setItem('username', inputUserName.value);
localStorage.setItem('email', inputEmail.value);
localStorage.setItem('password', inputPassWord.value);
}
function check() {
// Getting data from the register-form
var inputUserName = localStorage.getItem('username');
var inputPassWord = localStorage.getItem('password');
var username = document.getElementById('username');
var password = document.getElementById('password');
if (username.value == inputUserName && password.value == inputPassWord) {
alert('You have successfully logged in' + inputUserName);
} else {
alert('ERROR')
for(var i = 0; i < localStorage.length; i++){
alert(localStorage.key(i));
}
}
}
I figured it out, it was my HTML I had a name="Name" and it seemed to collide with the input that the user had changing to whatever was in the name="" in this case being Name, Email and Password.
If you want to get the input of the user in a specific field, you need to use something like:
document.getElementById('username').value;
You forgot to add the .value at the end.