How Login page is working in Jquery mobile? - javascript

I made a login page, i got the jquery code Can anybody explain me this CODE!??
Line by line! so that i know how the hell it is working! i have the code but i dont know how its work.. i am not that good in service integration and stuff
$(document).ready(function() {
$('#loginForm').submit(function() {
$('#output').html('Connecting....');
var postTo = 'login.php';
$.post(postTo,{username: $('[name=username]').val() , password: $('[name=password]').val()} , `
function(data) {
if(data.message) {
$('#output').html(data.message);
} else {
$('#output').html('Could not connect');
}
},'json');
return false;
});
});
`
In my html :
<!-- Start of first page -->
<div data-role="header">
<h1>Foo</h1>
</div><!-- /header -->
<div data-role="content">
<p id="output"></p>
<p>
<form method="post" id="loginForm">
Username: <input type="text" name="username"><br /><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Login">
</form>
</p>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /header -->
I basically wanna know what $.post is doing? and how?

$.post posts a request to a URL with optional parameters and returns a response.
Let's go through your example.
$.post(postTo,......
The first parameter is the URL to which you are posting the request. This is stored in the postTo variable. In this case it has been set to login.php.
$.post(postTo,{username: $('[name=username]').val() , password: $('[name=password]').val()},......
The next part contains the data you are passing to this script. You are passing values for "username" and "password" which are being retrieved from the value of an element with the name "username" $('[name=username]') and an element with the name "password" $(name=password) which in this case are your inputs for username and password.
A successful response from login.php will trigger the callback function. Any data returned will also be available to your function(data). This data can be JSON, XML or a string
It works the same as a standard form (except for the callback).
<form action="login.php" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
In the above code, the whole page will redirect to login.php where you would capture the username and password and process it to perform some action. With $.post, you do the same thing without actually redirecting the page. In your login.php script, you capture the posted username and password and return a value.
For instance, you could take the username and password, query your database and if you find a match return "success" or if it does not match you could return "failure". In your ..function(data).. you check to see if the returned value is "success" and perform an action otherwise you perform another action

Related

How do i encrypt password before send to php script?

I want to send the password encrypted to the server side script, and after match the pasword encrypted with the password on the database, if the passords match, redirect the user to the home page.
My Jquery function:
jQuery('#login_form').submit(function(){
var form_data = new FormData();
form_data.append('login', $('#lg-user').val());
form_data.append('password', CryptoJS.MD5($('#lg-password').val()));
jQuery.ajax({
type: "POST",
url: "processa.php",
data: dados,
success: function( data )
{
alert( data );
}
});
return false;
});
The form:
<form action="" id="login_form" method="post">
<?php
session_start();
if (isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" name="username" class="form-control"
placeholder="usuario">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="password" name="password" class="form-control"
placeholder="senha">
</div>
<div class="col-md-12">
<div class="text-center">
<input type="submit" value="Entrar" class="btn login_btn">
</div>
</div>
</form>
The problem is that everytime i send the form, the page reload.
Your approach is highly insecure.
By encrypting it client-side and matching what it sent with the DB, you are sending the data that "proves" the user is who they say they are to the server, so if someone were to get hold the database they would know what to send.
Also, MD5 is far too weak to secure a password today.
To keep the password safe in transmission to the server: Use HTTPS.
To keep the passwords in your database safe: hash them server-side as described in the Safe Password Hashing FAQ in the PHP manual.
To stop the regular form submission when you use the submit event to intercept it and use Ajax:
Capture the event object
Call preventDefault on it
Such:
jQuery('#login_form').submit(function(e){
e.preventDefault()

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

How to display modal form after submitting through AJAX

I Have a login in form inside a modal. After submitting the form i am getting success or failure message..let's say failure message. But when i am reopening the modal same message is appearing instead of log in form. After refreshing the page only modal is showing the log in form.
Here is my code....please help me how can i fix it so it will show the log in form when i reopen the modal after submission.
<!-- Sign in feature starts here -->
<div id="sign_in" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sign In</h4>
</div>
<div class="modal-body">
<div class="panel-body" id="form">
<form class="form-horizontal" role="form" method="post" id="log-in" >
<fieldset>
<div class="form-group">
<input class="form-control" id="username" placeholder=" Username or Mobile No." type="text" autofocus AutoComplete=off required>
</div>
<div class="form-group">
<input class="form-control" id="password" placeholder=" Enter Password" type="password" autofocus AutoComplete=off required>
</div>
<!-- Change this to a button or input when using this as a form -->
<button class="btn btn-lg btn-success btn-block" type="submit">Sign In</button>
</fieldset>
</form> </div>
</div>
</div>
</div></div>
<!-- Sign In feature ends here -->
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('submit', '#log-in', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : '<?php echo site_url('verifylogin');?>',
data : data,
success : function(data)
{
$("#log-in").fadeOut(500).hide(function()
{
$("#form").fadeIn(500).show(function()
{
$("#form").html(data);
if(data != null && data == "success"){ //redirect...
window.location.replace('home.php');
}
});
});
}
});
return false;
});
});
</script>
The problem is at $("#form").html(data);
Why are you removing the form HTML and replacing it with the data you are receiving ?
When are you putting back the form HTML in the modal? It is working after refresh because the page is getting loaded again.
In the previous case you have updated the DOM, removed the form HTML and replaced it with data that you are receiving. So the next time you open the modal you will get to see the same data.
try to change this part
$("#form").html(data);
if(data != null && data == "success")
{ //redirect...
window.location.replace('home.php');
}
TO
$("#form").html(data);
i.e. REMOVE THIS PART
if(data != null && data == "success")
{ //redirect...
window.location.replace('home.php');
}
Also add this div somewhere in your code; This is the div that returns the result from your PHP code.
<div id="form"></div>
If redirecting is your success. Then add the redirecting code in your success definition in the PHP code i.e.
<?php
echo 'please wait! redirecting...';
echo "<script>window.location.href='home.php';</script>";
?>
Ajax does not understand what your PHP means by success. Failure might be success to another person and failure to another person.
In your question, if someone enters wrong username or password. it is likely to redirect Because that is also a success.
Hope this helps

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.

jQuery tabs disabled after form submit

I have a form in a jQuery tab div that is loaded with AJAX:
<div id="tabs-2">
<form id="frmLogin" name="frmLogin" class="cmxform" method="post" action="actions/login.php">
<p>
<label>Username</label>
<input type="text" id="username" name="username" maxlength="30" />
</p>
<div class="clear"></div>
<p>
<label>Password</label>
<input type="password" id="password" name="password" maxlength="40" />
</p>
<p>
<input class="submit" type="submit" id="submit" value="Login" />
</p>
<div class="clear"></div>
</form>
</div>
The form submits to the listed PHP file. This .js file using the Form and Validation jQuery plugins submits the form via AJAX. The PHP file echoes back JSON data:
$(document).ready(function() {
$("#frmLogin").validate({
rules: {
username: {
required: true,
minlength: 6
},
password: {
required: true,
minlength: 6
},
},
submitHandler: function(form) {
$("#frmLogin").ajaxSubmit({
dataType: 'json',
success: processLogin,
})
}
});
function processLogin(data) {
if (data.un) {
$("div#tabs-2").slideUp(function() {
$("li#login").html('Welcome, '+data.fn+'');
});
} else {
alert("uh-oh");
}
}
});
This all works fine. I've got the link which previously read "Login" to read back a Welcome message. Now I want to replace that tab's contents (login form) with a ul of user options.
The problem: the link with the Welcome message no longer functions as a tab. When clicked, it directs the browser to the "ajax/loggedin.html."
I've tried restating the tabs function in the "loggedin.html" file and calling it in the processLogin function in "login.js". My next fix attempt will be to change the html content of the tabs-2 div in the processLogin function, but this seems like it will generate a lot of clunky code.
Any suggestions for preventing the disabling of the tab behavior?
This the classic when-code-is-run problem. You are setting the tab behavior to check for tabs and set them up. Then you load new code, but you haven't initialized the tab for these.
The solutions are to use delegate (or live) instead of direct click events or to initialize the tabs in the ajax callback. The latter is the best solution for this problem.

Categories