php web page password empty validation - javascript

I wanted to check if the username and password fields are empty.
If they are empty it should give a error message box and the message box should contain a message and a ok button.
When user clicks the ok button the msg box should close and user should see the login page.
For that i wrote the below code. but after pressing the ok button on error message box the web page address is remaining same but the content is not getting displayed , full white page is displayed.
you do refresh and page comes back.
This is the file i am opening in browser register.php
<?php
// configuration
require("../includes/config.php");
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
// else render form
render("register_form.php", ["title" => "Register"]);
}
// else if user reached page via POST (as by submitting a form via POST)
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// TODO
if (empty($_POST["username"]) || empty($_POST["password"]))
{
$message = "Username and/or Password empty.\\nTry again.";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>
And this is the form file register_form.php
<form action="register.php" method="post">
<fieldset>
<div class="form-group">
<label>Username :</label>
<input autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<label>Password :</label>
<input class="form-control" name="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<label>Password :</label>
<input class="form-control" name="confirmation" placeholder="Retype-Password" type="password"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Register</button>
</div>
</fieldset>
</form>
i want to see login page after clicking the ok button on the message box i do not want to see white page. please help

Related

custom error message shows and disappears on submit

I am using flask, html, css and javascript. So what I did was enter a error message in my login form as a new and set display: none. I validate the input credential by comparing values from a SQLite database i set previously. This validation is done inside the flask. When the form is submitted, it is validated inside the flask, however I created a javascript that changes the styling for the error message to display: block. This would show the error message for incorrect fields and the correct input users will be redirected to a new page and hence they wont see the error.
So I was hoping that the error message shows after the form is submitted for the login and the users that key in the right information will be redirected.
Flask:
#app.route('/', methods=['POST', 'GET'])
def tutor_login():
tutor_login_form = LoginAccount(request.form)
if request.method == 'POST' and tutor_login_form.validate():
session.pop('user', None)
admin_account = Admin.query.all()
tutor_account = Tutor.query.all()
for i in admin_account:
admin_id = i.admin_id_num
for j in tutor_account:
tutor_id = j.tutor_id_num
if admin_id == tutor_login_form.id_num.data:
admin_info = Admin.query.filter_by(admin_id_num=tutor_login_form.id_num.data).first()
admin_pass = admin_info.admin_password
if admin_pass == tutor_login_form.password.data:
session['user'] = tutor_login_form.id_num.data
return redirect(url_for('admin_main'))
elif tutor_id == tutor_login_form.id_num.data:
tutor_info = Tutor.query.filter_by(id_num=tutor_login_form.id_num.data).first()
tutor_pass = tutor_info.tutor_password
if tutor_pass == tutor_login_form.password.data:
session['user'] = tutor_login_form.id_num.data
return redirect(url_for('retrieve_tutor_account'))
return render_template('tutorlogin.html')
HTML:
<form class="" action="" method="POST" onsubmit="validate()">
<!-- Input fields -->
<div class="form-group mt-3">
<label for="id_num">Enter Tutor ID:</label>
<input type="text" class="form-control" id="id_num" placeholder="Enter Tutor ID" name="id_num">
</div>
<div class="form-group my-3">
<label for="password">Enter Password:</label>
<input type="password" class="form-control password" id="password" placeholder="Enter Password" name="password">
</div>
<div class="mb-3 text-center" id="error">
ID or Password entered is invalid! Please try again.
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary btn-customized">Login</button>
</div>
<div>
<p class="text-center my-3">Forgot your password? <br> Click here to reset</p>
</div>
</form>
Javascript:
<script>
var error = document.getElementById('error');
function validate(){
error.style.display = "block";
}
</script>
If you want to validate the credentials without a page reload, you need to use Ajax requests.
Where on clicking Submit, the JavaScript will first check if all fields all valid and filled and then send an Ajax request to the Flask app.
Depending on the response of the query you can either show a error message or redirect user to the page you want.
Here's a YouTube video for reference - https://www.youtube.com/watch?v=UmC26YXExJ4

How to show a success message to redirected page after submitting from another page using jquery in JSP?

I have a reset password form. After submitting it, it redirects to login page. However, it doesn't show any success message upon getting the successful reset password. And, I'm uncertain how can I do this as these are two different jsp files. And even if the login page uses the reset password javascript code, it still can't be able to show the conditional message. I am using java spring boot, jquery and javascript. This is my code:
resetPassword.js
$(".resetPassword").on('submit', function (e) {
e.preventDefault();
var password = $("#pass").val();
var confirmPass = $("#confirmPass").val();
if(password !== confirmPassword){
$(".perror").show();
}
else {
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
});
resetPassword.jsp
<form:form action="/reset_password" method="POST" class="resetPass" modelAttribute="resetPassword">
<div class="alert alert-danger perror" role="alert" style="display: none">Password not match</div>
<form:input type="hidden" path="token" />
<div class="form-group-row ">
<label htmlFor="passwordReset">Password</label>
<input type="password" id="pass" path="password" placeholder="Password" required/>
</div>
<div class="form-group-row ">
<label htmlFor="confirmPasswordReset">Confirm Password</label>
<input type="password" id="confirmPass" placeholder="Confirm Password" required/>
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form:form>
Now, this is the login.jsp in where I want the successful message which currently now I've been showing from alert box however that seems not a good design.
login.jsp
<form:form action="/login" method="POST" modelAttribute="user" >
<div class="alert alert-success successfulResetPassword" role="alert" style="display: none>Your password changed successfully. Please login using your email and password</div>
<input type="text" id="email" name="email" placeholder="email" required/>
<input type="password" id="password" name="password" placeholder="pass" required/>
</form:form>
now all I want, is to show the div class=successfulResetPassword after a user reset the password show that the display alter it's value to visible. But I haven't found any good way to this as reset password is using a different js file and from that submit button I'm redirected the whole scenario to login page. Even if the login page can access that js page still it can't have the value of changing display property :
$("#successfulResetPassword").show();. I tried to modify my code like this till now :
resetPassword.js
else {
$("#successfulResetPassword").show(); //it could've shown the msg, but can't because it's in button submit condition after redirected to login page which has no **resetPassword** class
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
And this is my backend code:
#PostMapping("/reset_password")
public String resetPasswordSubmit(Map<String, Object> model, #ModelAttribute("resetPassword") ResetPasswordDTO resetPassword){
model.put("pageTitle", Constant.PAGE_TITLE);
GenericResponse response = loginService.changePassword(resetPassword);
if(response.getStatusCode() == 200){
return "redirect:/login";
}
model.put("error", "error");
return "resetPassword";
}

JavaScript Validation Form not working

I'm trying to validate my form so that if the user doesn't enter the username or the password, he isn't allowed to login to the website. For some reason, when I do enter both the username and password fields, and click login, the login.html page doesn't appear. Any help?
<script>
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>
<form id="loginform" name="loginform" method="post">
<div>
<label hidden> Username</label>
<input type= "text" class="text" placeholder="Username" title="Username" name="username">
<span id="usernameError"></span>
<label hidden> Password </label>
<input type= "password" class="text" placeholder="Password" title="Password" name="password">
<span id="passwordError"></span>
Forgot password?
</div>
<div class="button-container">
<a href="login.html" target="_blank"> <input type= "submit" value="Login" class="login"/>
</a>
<input type= "button" value="Sign up" class="login signup"/>
</div>
</form>
You had your submit button wrapped in an a element that was pointing to login.html, which is not how to properly redirect after a form submission. This will also cause problems with handling events because of event bubbling and/or capturing.
In actuality, you haven't specified where the form should send its data to in your form tag:
<form id="loginform" name="loginform" method="post">
Which (by default) means that the form will send its data to the current page (causing the same page to reload, but have the form data accessible to it in this updated load).
To send the data to a different page/resource, the form needs to have an action attribute which specifies the path to the destination:
<form id="loginform" name="loginform" method="post" action="login.html">
See this for details on submitting forms.
Stack Overflow's code snippet environment doesn't allow for form submissions, but check out this Fiddle which has an updated version of your code that works.

HTML / js. Need two different forms on one page submits separately

I can't find any answer then ask:
I have to different forms on the page: the one is "ask for call" (placed on every page on the site) and the second is a simple "contact form" (placed only on contact page).
Both are validates without problems, do they are created for also good on the different page. Both has fields which are required. They has different names and IDs.
The error occurs when user on the contact page. There are two forms together. By the order contact is first. And when I use it, a mail sends.
But when I try to send call request with the second form on the page, it doesn't action because on the first form required wasn't filled or didn't match restrictions.
Why submit button from the second form takes data from the first?
Below forms in the order on the contact page and processing functions.
First form (contact)
<form id="message" name="contact_message" onsubmit="return false;" method="post">
<div class="hover">
<label for="message-name">Введите ваше имя:</label>
<input id="message-name" name="name" type="text" placeholder="Имя" title="Пожалуйста, введите ваше имя." required>
</div>
<div class="hover">
<label for="message-email">Введите ваш email адрес:</label>
<input id="message-email" name="email" type="email" placeholder="xxx#xxx.xx" title="Пожалуйста, введите корректно ваш email." required>
</div>
<div class="hover">
<label for="message-text">Введите ваше сообщение:</label>
<textarea id="message-text" name="text" placeholder="Текст сообщения" title="Пожалуйста, введите текст сообщения. Минимум 9 символов." minlength="9" required></textarea>
</div>
<input type="hidden" name="type" value="contact_page">
<button id="submit-contact" class="empty blue button medium" type="submit">Отправить</button>
<div class="c-clearfix"></div>
</form>
The second form
<form id="call-ask-form" name="call-ask-form" class="full-width" onsubmit="return false;" method="post">
<label for="phone-name">Ваше имя</label>
<input id="phone-name" type="text" name="name" placeholder="Введите ваше имя" minlength="2" required>
<label for="phone-phone">Ваш номер телефона (только цифры)</label>
<input id="phone-phone" type="text" name="phone" placeholder="+41234567890" maxlength="16" required>
<label for="phone-time">Время в формате ЧЧ:ММ, с 9 до 17 в будние дни, когда вы ожидаете звонок.</label>
<input id="phone-time" type="text" name="text" placeholder="ЧЧ:ММ" maxlength="5">
<input id="type" name="type" type="hidden" value="call_ask">
<button form="call-ask-form" id="call-submit" class="filled green medium full-width button" type="submit">Отправить запрос</button>
</form>
JS
And here the page_type variable gets data from the first form every time I push submit on the second form. And switch cases on CONTACT, but CALL REQUEST.
$(document).ready(function() {
$("#submit, #call-submit").click(function() {
var proceed = true;
var page_type = $('input[name=type]').val();
//validation
if(proceed)
{
var form;
//choosing type of a message
switch (page_type) {
case 'contact_page' :
// preparing data from CONTACT form
break;
case 'call_ask' :
// preparing data from CALL REQUEST form
break;
case 'calculator' :
break;
default :
}
// ajax post data
$.post('/assets/components/mailer2.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error" style="background-color: red; color: white;">' + response.text + '</div>';
} else {
output = '<div class="success" style="background-color: green; color: white;">' + response.text + '</div>';
}
$(form).append(output).slideDown();
}, 'json');
}
});
Why this happens? Kindly asking you for help.
In the line $('input[name=type]').val();, this will always try to find the value of the first input matching the name criteria on the whole page.
But, note that both of your forms have inputs with the same name.
Javascript will not be very friendly when multiple elements have the same name. Instead, you will either need to rename them or ensure that you better reference which one you are trying to get:
The below code will get you the correct page_type: (Note that in events, this will be set to the current element which in the below case will be one of the <form /> tags which you can use to only traverse it's children using $(this).find(...) as opposed to $(...))
$('form').on('submit', function(e){
var page_type = $(this).find('input[name=type]').val();
alert(page_type);
e.preventDefault();
})

How to show session errors in the index page for wrong id password?

I think this question has been answered many times. But still i didn't find a suitable solution. i want to display "wrong id/password" message in my admin_login.php page itself when my id and password do not match. how to do it? Please help. Here is my code
admin_login.php
<body>
<script type='text/javascript'>
<?php
if(isset($_SESSION['error_message']))
{
?>
alert("<?php echo $_SESSION['error_message']; ?>");
<?php
unset($_SESSION['error_message']);
}
?>
</script>
<section class="container">
<div class="login">
<h1>Login to Admin Panel</h1>
<form method="post" action="admin_logincode.php" enctype="multipart/form- data">
<p><input type="text" name="uname" id= "uname" value="" placeholder="Username or Email"></p>
<p><input type="password" name="password" id="password" value="" placeholder="Password"></p>
<p class="remember_me">
<label>
<input type="checkbox" name="remember_me" id="remember_me">
Remember me on this computer
</label>
</p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
</section>
</body>
This is my php code: admin_logincode.php
<?php
include ("connection.php");
session_start();
$uname=$_POST['uname'];
$password=$_POST['password'];
if($uname=="admin" && $password=="2015admingoswami")
{
$_SESSION['uname']=$uname;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + 120;
header("location:admin_home.php");
}
else
{
$_SESSION['error_message']="Wrong Username or Password";
header("location:admin_login.php");
}
?>
I have done the coding part to display the error message but still it didn't work. Please help me out.
Make sure you're not forgetting to call session_start() on the page where you want to print the error.
You also can make an AJAX call (with jQuery) when the submit button of your admin_login.php page is clicked, and the target of the call would be admin_logincode.php. The result of the AJAX call could be appended to any part of your form (a DIV for instance) so you can append here "wrong password" without refreshing the login page. If the login/pass match, then admin_logincode.php will initiate a session.
Just check on your index page if the session exists, almost like as you did.
//if session exists, then user is authentified
if (isset($_SESSION['auth'])) {
//display the user menu, or whatever
}
//else display the login form
else {
display_login();
}
Don't forget to "never trust the client" so you have to be careful when handling data posted by the user. Check special chars, length...and pay attention to fields you use to perform MySQL requests.

Categories