JavaScript stops working when I refresh page - javascript

I have this block of JavaScript code:
var input = document.getElementById("password_field");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("login").click();
}
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
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;
var email_verified = user.emailVerified;
document.getElementById('user_para').innerHTML = "You are logged in as<strong> " + email_id + "</strong>.";
if (email_verified === false) {
document.getElementById('user_verified').innerHTML = "<strong>You are not verified. Please check for an email from perason for a verification link. You will not be able to access anything without verification.";
} else {
document.getElementById('user_verified').innerHTML = "";
document.getElementById('sandboxaccess').style.display = "block";
}
}
} else {
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
function login () {
var userEmail = document.getElementById('email_field').value;
var userPass = document.getElementById('password_field').value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
});
}
function logout() {
firebase.auth().signOut();
}
It works fine initially, but when I refresh the page, all of the JavaScript stops working. It works perfectly fine on Apache localhost (refreshing works on localhost too). What is the solution to this?
Here it is before refresh:
before refresh
Here it is after refresh:
after refresh
The logout button is in both.
Errors on console

Remove this line of code from your program:
var user = firebase.auth().currentUser
You already have a user object as the parameter of your callback function. The currentUser returned here might actually be wrongly null and overwriting the correct one being passed in.

I think the code is executed before the DOM is loaded.
how about this:
document.addEventListener('DOMContentLoaded', function (){
// your code
});

Related

Accessing child node properties in Firebase RTD

I have .js file where I loop through Firebase real time database to find email and password of registered users which is stored under /users tree in database where each child is randomly generated unique id which has user information. I am getting email and password information from form element. Problem is the alert messages in checkMessage are not executed when email and password do not equal same. Alert message should be displayed but only page refreshes.
Database:
----/Users
--------/XJIGFDMDKGD
-------------email: "a#b.com"
-------------password: "12345"
--------/XJFGNRIENGJ
-------------email: "c#d.com"
-------------password: "67890"
My code:
document
.getElementById('loginForm')
.addEventListener('submit', formSubmit);
function formSubmit(e) {
e.preventDefault();
document.querySelector('.alert').style.display = 'block';
// Get Values from the DOM
let email = document.querySelector('#email').value;
let password = document.querySelector('#password').value;
//check message values
checkMessage(email, password);
//Form Reset After Submission
//document.getElementById('loginForm').reset();
}
checkMessage function:
function checkMessage(email, password) {
var usrs = firebase.database().ref('users');
usrs.on("child_added", function(snapshot) {
var user = snapshot.val();
if (user.email == email) {
if (user.password == password) {
} else {
}
} else {
document.querySelector('.alert2').style.display = 'block';
setTimeout(function() {
document.querySelector('.alert2').style.display = 'none';
}, 7000);
document.getElementById('loginForm').reset();
}
);
}
The error was caused by syntax problem, an extra brace at the end of the following section of code, as well as a misplaced parentheses. Fixed solution:
var users = firebase.database().ref('users');
users.on("child_added", function(snapshot) {
var user = snapshot.val();
if (email == user.email) {
if (password == user.password) {
}
} else {
};
});

"if" statement for validating a form doesn't work properly

I have this newsletter form with email input generated with wordpress plugin. Form action is set to a sub-page. I want to check if given email adress is correct - if not, I want to print an alert message.
let emailField = document.querySelector('.email').value;
const regEx = /\S+#\S+\.\S+/;
let submitBtn = document.querySelector('.btn-submit');
let form = document.querySelectorAll('.newsletter-container > form');
function validateEmail() {
if (regEx.test(emailField) == false) {
alert('!!!');
event.preventDefault();
} else {
form.submit();
}
}
submitBtn.addEventListener('click', function (event) {
validateEmail();
});
My problem is, when I type a correct email adress I still get alert and button default event is prevented from action.
What am I doing wrong?
strange construct but anyhow
let submitBtn = document.querySelector('.btn-submit');
function validateEmail() {
var regEx = /\S+#\S+\.\S+/;
let emailField = document.querySelector('.email').value;
if (regEx.test(emailField) == false) {
alert('!!!');
event.preventDefault();
} else {
let form = document.querySelectorAll('.newsletter-container > form');
form.submit();
}
}

Data retrieval query for firebase not working

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 );
}
}
});

i need help for login page

I need help for a login page using JavaScript. So far I have following code:
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var coruser = "admin";
var corpass = "admin";
if (user.value == coruser) {
if (pass.value == corpass) {
// Like you must login to see the page
} else {
window.alert("incorrect password or name");
}
} else {
window.alert("incorrect password or name");
}
}
I want it like after login show the page like you must login to see the page.
Any ideas?
Your function should look like this if you want to redirect user to your home page after checking the username.
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var coruser = "admin";
var corpass = "admin";
if (user.value == coruser) {
if (pass.value == corpass) {
window.location.href = "your page url";
} else {
window.alert("incorrect password or name");
}
} else {
window.alert("incorrect password or name");
}
}
Note: this is not a way to handle authentication.

if statement in jQuery not working in Chrome or Safari

I have the following code that is working in IE 8 but not in Chrome or Safari:
$(document).ready(function(){
$('.goRedIMG').on('click',function(event){
var ischecked = false;
var isOKtoSubmit = true;
var alertMessage = 'No tools have been selected';
var statusvar = '';
var transferstatusvar = '';
var action = $('#uTransaction option:selected').html();
$('.chkaction').each(function() { //loop through each checkbox
statusvar = $(this).closest('tr').children('.recordStatus').html();
transferstatusvar = $(this).closest('tr').children('.transferstat').html()
if($(this).prop('checked')) {
ischecked = true;
//alert(action);
// alert(statusvar);
// alert(transferstatusvar);
if (action == 'Recover'){
if (statusvar != 'OOS'){
// alert(statusvar);
isOKtoSubmit = false;
alertMessage = 'One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK';
}
}
if(isOKtoSubmit && ischecked !== false && action !== '--Select One--'){
$('#toolActions').submit();
}else {
alert(alertMessage);
}
});
If a user chooses Recover and chooses a record that has a status that is in 'OOS' they are getting the alert message in Chrome that the record does not have the correct status. In IE if you choose the same record the alert message does not appear and that would be correct.
When I use your code like this:
var action = 'Recover';
var statusvar = 'OOS';
if (action == 'Recover') {
if (statusvar != 'OOS') {
alert('One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK');
}
}
in both browsers it runs correctly. I think you have problem with your data.
In your original code try to use
alert(statusvar + ' - length:' + statusvar.length)
And check the character lenght of the variable. This way you can see if there is any funny character in your statusvar variable.

Categories

Resources