Window.location not working in Javascript - javascript

So I'm new to JS, and I wanna redirect the user to another page...
My code:
// Below function Executes on click of login button.
function validate() {
redirectTo =
window.location.protocol + window.location.host + "/dashboard.html";
var username = document.getElementById("userName").value;
var password = document.getElementById("passWord").value;
if (username == "admin" && password == "password") {
window.location = redirectTo; // Redirecting to other page.
return false;
} else {
alert("NANI!!!");
}
}
I know this is not a secure way to auth, but relax it's just a portfolio project

You should append the '//' after window.location.protocol which mentioned by #Vasan.
Using ES6 template strings would make it clear.
function validate() {
const redirectTo = `${window.location.protocol}//${window.location.host}/dashboard.html`;
const username = document.getElementById('userName').value;
const password = document.getElementById('passWord').value;
if (username === 'admin' && password === 'password') {
window.location = redirectTo; // Redirecting to other page.
return false;
} else {
alert('NANI!!!');
}
}

It should be window.location.href = redirectTo.

Related

JavaScript stops working when I refresh page

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

javascript redirection doesnt seem to work

I use JavaScript for a simple function, however my redirection doesn't work. I thought it was because of the files, but they seem to be in the same folder. See below file structure:
Here is my relevant code:
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "mr.X" && password == "x123456") {
alert("Login successfully");
window.location = "Dashboard.jsp"; // Redirecting to other page.
return false;
} else {
alert("You have inserted wrong credentials");
}
}

Check if user auth id exist in firebase database before navigating to a new page

After a user sign in successfully, I want to use the User UID to verify the user has selected the right school, I have been able to achieve this task, but the problem is, I have to click the login button twice before an action takes effect.
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
//After signing in, use the user auth id to check if the user exist in the selected school
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
}
It is very unusual to have an onAuthStateChanged listener in a click handler like that. More likely you want something like:
...
} else {
toggleSignIn();
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
By the way: if you can look up the school for the user with a query, is there any specific reason why you don't simply prepopulate that value for them in the form?
Your code has a flaw. onAuthStateChanged listener is attached every time the button is clicked. This could add multiple listeners and the same code triggered multiple times after each repeated click. onAuthStateChanged listener should be attached only once when the document is loaded. Your code should be something like:
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
}
}
document.onload = function () {
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
I assume toggleSignIn() function is used to sign in and will change the firebase AuthState on successful sign in.

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.

Javascript, ajax and django not redirecting page and returning value as text

I am trying to make a Django and Ajax based Login View with Mobile Number verification via a One Time Password (OTP). When the User signups, his mobile number is sent an OTP, which he has to enter and confirm.
Now, let's say the user did not authenticate his mobile number before and now tries to login into the website, I want him to first verify the mobile number via the OTP that was sent to his mobile number and then he can further log into the site.
My code for signup in views.py is:
def signup(request):
if request.method == "POST":
first_name = request.POST.get("fname")
last_name = request.POST.get("lname")
mobile = request.POST.get("telephone")
email = request.POST.get("email")
password = request.POST.get("password")
try:
#mobilecheck = Customer.objects.get(mobile=mobile)
emailcheck = Customer.objects.get(email=email)
except ObjectDoesNotExist:
user = Customer.objects.create_user(email, password, mobile=mobile, first_name=first_name, last_name=last_name, is_active=False)
otp = randint(1000,9999)
message = "Verification code for Delimedy.com is : " + str(otp)
mOTP = MobileOTP(customer=user, otp=otp)
mOTP.save()
sendotp(mobile, message)
user = authenticate(username=email, password=password)
auth_login(request, user)
return HttpResponse("success")
else:
return HttpResponse("conflict")
else:
return render(request, "registration/signup.html", {
"title":"Signup",
})
And code for login in views.py is :
def login(request):
auth_logout(request)
if request.method == "POST":
email = request.POST.get("email")
password = request.POST.get("password")
user = authenticate(username=email, password=password)
if user is not None:
auth_login(request, user)
if user.is_active:
return HttpResponse("success", content_type="text/plain")
else:
return HttpResponse("notverified", content_type="text/plain")
else:
return HttpResponse("mismatch", content_type="text/plain")
else:
return render(request, "registration/login.html", {
"title":"Login to Delimedy"
})
And the contents of my .js file for the Ajax function calling is:
$('#login-button').on('click', function(){
var preloader = $('#overlay-screen');
preloader.removeClass('hide');
var redirectTo = $(this).attr("rel");
var email = $('#email');
if(email.val().length == 0) {
email.removeClass('valid');
email.addClass('invalid');
preloader.addClass('hide');
return;
}
var password = $('#password');
if(password.val().length == 0) {
password.removeClass('valid');
password.addClass('invalid');
preloader.addClass('hide');
return;
}
var csrf_token = $("input[name=csrfmiddlewaretoken]").val();
var rememberme = $('#remember').is(':checked');
var dataString = 'email='+email.val()+'&password='+password.val()+'&csrfmiddlewaretoken='+csrf_token;
$.ajax
({
type: "POST",
url: "/account/login/",
data: dataString,
cache: false,
success: function(data)
{
preloader.addClass('hide');
if(data == 'email_blank') {
email.removeClass('valid');
email.addClass('invalid');
return;
}
else if(data == 'password_blank') {
password.removeClass('valid');
password.addClass('invalid');
return;
}
else if(data == 'success') {
window.location.href = "/";
}
else if(data == 'notverified') {
window.location.href="/account/login/"
}
else if(data == "mismatch") {
alert("Mobile Number and Password doesn't match.");
}
else {
alert(data);
}
}
});
});
The problem with the login form is that, If try to login and the login is successful, instead of redirecting to the page, it opens a page with the text "success" and let's say the user is registered and not active but tries to login, does not get redirected to verifyotp page but a page with just "notverified" written. How do I fix it?
rather than: return HttpResponse("success", content_type="text/plain")
You should have: return redirect(myurl)
https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#redirect
Don't know if it is the question, but django will refresh current page after a click on the button, to prevent this you could add in js:
return false;
or
e.preventDefault();

Categories

Resources