I have a php file stored remotely. It uses post to take 2 variables, "username" and "password", which will then echo either Valid or Invalid depending on it's existence in my database. I currently use this with my android application to log users in.
I would like to use this same script for logging into my website that I am building. I need to be able to pass 2 variables that I have obtained from an HTML form to a javascript function which will take the variables, run them though the php query, read the echoed output and decide to return true or false to the form. Below is the code I currently have for the script
Javascript code:
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase == "valid")
return true;
else
return false;
});
}
</script>
HTML form:
<form action="Main.html" method="post" onsubmit=" return Login();">
Username: <br>
<input type="text" name="username" id="username"><br>
Password: <br>
<input type="password" name="password" id="password"><br><br>
<input type="submit" value="Login">
</form>
Currently, it always sends the user to my Main.html page with any non-empty username/password input.
I'm not very well versed in these two languages, but I need to learn quickly as they are important for my Senior Project class semester, and especially these next two weeks. Is this possible to do with Javascript and HTML only? Some pointers will be much appreciated! Thank you!
You actually are almost all the way there. You just need to return false from your Login function to prevent the default action of the form from triggering (which is to redirect to main.html). Then, instead of relying on the form to redirect the user, you will need to do so yourself via javascript.
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase() === "valid")
window.location.href = "./Main.html"; //redirect the user
else
return false;
});
return false
}
</script>
Related
I am using Flask Framework..
I have a form tag in the front end for login id and password and a submit button.
I want to use JavaScript in the front end to verify the data provided by the user in the form field and then if everything is okay, then I want to send the data provided by the user to the back end server and process it using python..
But how can I control the process that when the user click on the submit button the control will go to the JavaScript code and then after validation, the data is sent to the back end server
In the snippet I have given a dummy example. In that my doubt is how to first send the control to the validate_login_form() written in Java Script and then after validation the control should go to the {{url_for('home')}} written in the action part using the Jinja2 template engine
Here the trouble that i am having is, after filling up the form, when the user clicked of the submit button, the control goes fine to the Java Script function written to validate the form but even if the Java Script returns false, the control automatically goes to the back end server.
But what i want to do is if the Java Script returns false, the control should stop there and ask the user to again fill in the form.
function validate_login_form(){
let login_id = document.getElementById('login_id').value
let password = document.getElementById('password').value
if(login_id == '' && password == ''){
alert('please enter the login id and password')
return(false)
}
else if(login_id == '' && password != ''){
alert('please enter the login id')
return(false)
}
else if(login_id != '' && password == ''){
alert('please enter the password')
return(false)
}
else{
if(login_id == 'test' && password == 'test'){
return(true);
}
else{
alert('please enter the valid login id and password')
return(false)
}
}
}
<html>
<head>
</head>
<body>
<form action="{{url_for('home')}}" onsubmit="validate_login_form()">
<label for="login_id">LogIn</label>
<input type="text" name="login_id" placeholder="login Id" id="login_id">
<label for="password">Password</label>
<input type="password" name="password" placeholder="password" id="password">
<br><br>
<input type="submit" value="submit" >
</form>
<script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
</body>
</html>
Simple: https://www.w3schools.com/jsref/event_onsubmit.asp.
There your go:
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
return true;
}
</script>
HTML from example:
<form method="POST" id="myForm">
<input type="email" name="email" id="email"/>
<input type="password" name="password" id="password"/>
<button type="submit">Login</button>
</form>
javascript:
var myForm = document.getElementById("myForm");
myForm.onsubmit = function(e){
e.preventDefault();
// validate here and produce data
fetch('/mypage', {
method: "POST",
credentials: "include",
cache: "no-cache",
body: data,
headers: new Headers({
"Content-Type": "application/json",
}),
})
.then((response) => {
if (response.status !== 200) {
// handling if status is not ok(200)
}
response.text().then((res) => {
// response handling
if(res === "success"){
// redirect to homepage or do anything
} else {
// something went wrong
}
});
})
.catch((err) => {
// error handle
});
}
Flask/Python:
from flask import request
#app.route('/mypage', methods=['GET', 'POST'])
def myPage():
if request.method == "POST" and request.json:
data = request.json
# send data to database
return 'success', 200
The only problem here in the codes are in the form tag in html,
I should have written onsubmit=return validate_login_form()
instead of onsubmit=validate_login_form()
By this code if the JavaScript function returns true then the page will be redirected to the url written in the action field of the form tag
and if the JavaScript function returns flase then the control will remain in the same page without being redirected.
That's how the flow can be controlled
function validate_login_form(){
let login_id = document.getElementById('login_id').value
let password = document.getElementById('password').value
if(login_id == '' && password == ''){
alert('please enter the login id and password')
return(false)
}
else if(login_id == '' && password != ''){
alert('please enter the login id')
return(false)
}
else if(login_id != '' && password == ''){
alert('please enter the password')
return(false)
}
else{
if(login_id == 'test' && password == 'test'){
return(true);
}
else{
alert('please enter the valid login id and password')
return(false)
}
}
}
<html>
<head>
</head>
<body>
<form action="{{url_for('home')}}" onsubmit="return validate_login_form()">
<label for="login_id">LogIn</label>
<input type="text" name="login_id" placeholder="login Id" id="login_id">
<label for="password">Password</label>
<input type="password" name="password" placeholder="password" id="password">
<br><br>
<input type="submit" value="submit" >
</form>
<script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
</body>
</html>
I have a really simple login form that I want to check if the credentials are right (so I don't have to reload a page if the credentials are wrong) before submitting the form.
The problem I'm running into is the response from the AJAX call. When the program decides that the user has supplied the correct credentials, this code works like a charm. In addition, when performing the two checks prior to the AJAX call (whether the user filled in the password input field or if the username is valid), the code works perfectly. It returns an error message and returns the false boolean value, preventing the form from submitting. But, when the response from the server comes back and it is found that the credentials are not correct, the error message displays, but the page also reloads (therein displaying an additional error message). Why is the form still submitting, even though I'm returning false? I've checked the JavaScript console, there are no errors. I've also tried inverting the if statement, checking if ajax.responseText === "true", to the same result. I've tried adding a return false beneath the ajax.onreadystatechange call, but that just prevents the form from submitting at all (regardless of the response from the server).
Here is the form code:
<form method="POST" action="/afton/" onsubmit="return checkForm()">
<label for="username">Username:</label>
<input type='text' id='username' name='username' placeholder='Enter username...' required>
<label for="password">Password:</label>
<input type='password' id='password' name='password' placeholder='Enter password...' required>
<div class="form-buttons">
<button type='submit' name='action' id="loginButton" value='login'>Login</button>
<button type='button' id='register'>Register</button>
</div>
</form>
Here is the js function:
// Function that checks whether the user supplied correct credentials
function checkForm() {
// Get the password provided and the server message div on the page
const messageBox = document.getElementById("server-message");
const password = document.getElementById("password").value;
// If password is blank, return error message and return false
if (password === "") {
messageBox.innerHTML = "<p class='badMessage'>Please fill in the password!</p>"
return false;
}
// If the username input tag doesn't contain the 'goodBorder' class received upon validation of username, return error and false
if (!usernameInput.classList.contains("goodBorder")) {
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
return false;
}
// AJAX call that posts the info via JSON to check
const ajax = new XMLHttpRequest();
ajax.open("POST", "index.php?action=ajaxLogCheck", true);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send(JSON.stringify({"username":usernameInput.value, "password":password}));
// Handles the AJAX response
ajax.onreadystatechange = function () {
if (ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText !== "true") {
messageBox.innerHTML = ajax.responseText;
return false;
}
return true
}
}
}
And here is the PHP code that handles the AJAX:
// Get posted JSON encoded data
$data = json_decode(trim(file_get_contents("php://input")), true);
// Filter and sanitize the supplied username and password
$username = filter_var($data['username'], FILTER_SANITIZE_STRING);
$password = filter_var($data['password'], FILTER_SANITIZE_STRING);
// Get user data by the username and check the username against the password
$userData = getClient($username);
$hashCheck = password_verify($password, $userData['password']);
// Check response from the hashCheck and return the result
if ($hashCheck) {
echo "true";
exit;
}
logAtt($username, $_SERVER['REMOTE_ADDR'], false, getBrowser($_SERVER['HTTP_USER_AGENT']));
sleep(0.5);
$rands = array("Sorry, the username and/or password doesn't match our database. Please try again.", "Sorry, we don't recognize those login credentials. Please try again.", "Sorry, that login was incorrect. Please try again.", "Incorrect, please try again");
$randResult = array_rand(array_flip($rands));
echo "<p class='badMessage'>$randResult</p>";
// Just the point in AJAX function where you were returning True or
// False...Just Assign RESULT = 0 for False and
// RESULT = 1 for True
// .....SUppose You password matches so you were returning True..
// Dont do that...Instead Just Assign RESULT = 0 in that place and
// and out of the ajax Block paste this 'return Boolean(RESULT)'
// if RESULT = 0 then it will return False else it will return True
// Function that checks whether the user supplied correct credentials
function checkForm()
{
// Initialize a Variable Here Say RESULT
var RESULT = 0;
if (password === "")
{
RESULT = 0;
}
else if (!usernameInput.classList.contains("goodBorder"))
{
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
RESULT = 0;
}
// After this Put the ajax function and if you want to return False
// then simply assign RESULT = 0 instead of 'return false' else assign
// RESULT = 1 instead of 'return true'
return Booelan(RESULT);
// THis line is main Part this is returned by checkForm() function
}
// If I am still not clear, then I'll be happy to explain it on Google Meet.! :)
I am creating authentication module with prompt in javascript.
Here is my code:
var pass1 = prompt('Please Enter Your Password',' ');
var originalPass = "mypassword";
if(pass1 == "mypassword"){
return;
}
else{
pass1 = prompt('Wrong Password. Please Enter Valid Password',' ');
}
HTML
<html>
<head></head>
<body>
<p>Hello, You are logged in </p>
</body>
</html>
In my code, if I enter the wrong password, the program control goes to else loop and display another prompt password field, when I enter the wrong password again at the second time, it loads the page and displays the HTML content.
What I want to do is, I don't want to get load the page until the user enters the right password.
If you get the correct password either use a innerHTML to write the content to your dom, or here I have used document.write.
To ask the password continuously from user, add a while loop and break it only if the condition is true.
var pass1 = prompt('Please Enter Your Password');
var originalPass = "mypassword";
while (1) {
if (pass1 == "mypassword") {
document.write("<html><head></head><body><p>Hello, You are logged in</p></body></html>");
break;
} else {
pass1 = prompt('Wrong Password. Please Enter Valid Password');
}
}
So I have a login form. What I want I am currently doing is submitting the form using action="" etc.. with an onSubmit even with my form validation inside the javascript function validate(). Currently though it will submit the form and validate at the same time. What I want to happen is for it to not submit the form, or to cancel it as soon as we get into the validate function. And then if the forms are valid, submit the form.
This is my logic behind what I want to do
function validate() {
stopFormSubmit();
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
submitForm();
} else {
displayErrors();
}
}
My form looks like this
<form onSubmit="validate()" name="basicForm" id="basicForm" class="basicForm" action="login.php" method="post" autocomplete="off">
Is there anyway to do this?
The form does validate and then submit. Validation just takes very little time.
What you really want to do is to stop the form if it fails validation.
Using intrinsic event attributes, return false to stop the form being submitted. Since that is determined by the success of the validation, you need to return true or false from validate and then return that from your event handler.
onSubmit="return validate()"
and
function validate() {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
return true;
} else {
displayErrors();
return false;
}
}
Modern code would use unobtrusive JavaScript and bind the event handlers programatically. Then it would use the Event object to control that happened to the default behaviour. Since you are already using jQuery, we can use that to perform the event binding.
Remove the onsubmit attribute entirely.
jQuery('form').on('submit', validate); // Run this after the form exists in the DOM
and
function validate(evt) {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
// Do nothing
} else {
displayErrors();
evt.preventDefault();
}
}
I suggest to use jQuery Validation plugin, if possible.
Another idea - to do like here:
1. onSubmit="return validate()"
2. Update function:
function validate() {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
submitForm();
// or you can simply return true to allow form data submitting
} else {
displayErrors();
return false;
}
}
When a form submit button is clicked, a function to validate all the field is to be called. Nothing is to happen, however, if the validation fails.
I am using mailto: as my action, does this make a difference?
I would like to get clarification on two things:
Is this the correct way to call a function when clicking the submit button?
$(document).ready(function(){
$('#contactForm').submit(function(){
checkMail();
});
});
Can I still validate the fields even though I'm using mailto:?
Here is the rest of the code:
function checkEmail(){
var email = document.contact.email.value;
if(email == "") {
document.getElemtById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
HTML:
<form name="contact" action="mailto:exampleemail#hotmail.com" method="post">
<li>
<label for="email">Email</label>
<input id="email" type="text" name="email" placeholder="Enter Email Address">
</li>
<span id="email_error"></span>
Further, I don't get an error message on clicking submit.
No, you need the event handler to return false in case the validation failed. This will prevent the action from being executed, i.e. the mail program from being launched.
we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
Source
Modify it like this:
$(document).ready(function(){
$('#contactForm').submit(function(){
return validate();
});
});
Of course, this implies that the validate() function needs to actually return false in case the validation fails, and true otherwise.
Further you are missing id="contactForm" on your <form> tag.
Also, you need to grab the email value correctly:
var email = $("#email").val();
There's another mistake: You misspelled getElementById(). Here's a corrected version:
function checkEmail() {
var email = $("#email").val();
if (email == "") {
document.getElementById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
Or alternatively, using all jQuery:
function checkEmail() {
var email = $("#email").val();
var $error = $("#email_error");
if (email == "") {
$error.html("No Email Address");
return false;
}
else {
$error.html("");
return true;
}
}
Here's what you need:
$(document).ready(function(){
$('#contactForm').submit(function(){
if (!validate()) {
return false; // Prevent the submit
}
});
});
For validating the fields of your form, before sending it, you can use the jQuery's validation plugin:
$(document).ready(function(){
$("#contactForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
});
Check the online doc for more information and examples: http://docs.jquery.com/Plugins/Validation#Validate_forms_like_you.27ve_never_been_validating_before.21