How to create a login script using PHP and JAVASCRIPT? - javascript

I have a php file for comparing the inserted data in input element of HTML.
then, if I click the button, I want to trigger it by JavaScript.
I have a sample code with php, if I used this in html file, this works perfectly fine, but then I have no idea on how to use this in JavaScript.
<?php
include("php_functions/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header("location: .php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
HTML:
<form action="" method="POST" id="index-login">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>

First your code has alot of flops.
1.) You are saving password as plaintext, you will need to hash your password using php default password hashing mechanism.
2.) Your code is vulnerable to session Fixation attack. You can mitigate that using session regenerate_id as below
session_regenerate_id();
I will add it at your php script
3.) Session hijacking can only be prevented by ensuring that your site runs under https and not just http
4.) You are passing session username without sing htmlentities or htmlspecialchars functions.
Remember to do that when displaying session username on welcomepage.php
To answer your question, You can do that with Jquery/Ajax.
In the code below, am submitting your form using signin id attributes as can be seen in the jquery/ajax code below.
The code below displays all the actions triggered by the ajax/jquerycode
<div id="loader"></div>
<div id="result"></div>
Remember to include jquery.min.js files to ensure that it works
so here is your login.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
}
});
}
})
});
</script>
<form action="" method="POST">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
login.php
<?php
include("php_functions/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
//prevent session fixation attack
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("location: .php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>
Finally, in case if the form does not get submitted, you can remove just tis two the form elements
<form> </form> and it will work
Updated section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
$('#fadeoutResult').delay(5000).fadeOut('slow');
}
});
}
})
});
</script>
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="password"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input id="RememberMe" name="rememberme" type="checkbox" />
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<div id="loader"></div>
<div id="result"></div>
<div id="fadeoutResult"></div>
<button type="submit" class="btn btn-primary hidden-xs" id="signin">
Sign In Now
</button>
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
login.php
<?php
/*
//testing post data....
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = $_POST['username'];
echo $mypassword = $_POST['password'];
}
*/
include("php_functions/config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
//prevent session fixation attack
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("location: welcome.php");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>',
echo '<script type="text/javascript">',
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");',
echo '}, 100);</script>';
}
}
?>

There are many ways to collect data from a form, in my opinion the most practical is to use FormData. And the way to communicate javascript with php code is to use ajax. Please look at the following example.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="" method="POST" name="index-login" id="index-login">
<div class="form-group mb-lg">
<label>Username</label>
<div class="input-group input-group-icon">
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-user"></i>
</span>
</span>
</div>
</div>
<div class="form-group mb-lg">
<div class="clearfix">
<label class="pull-left">Password</label>
Lost Password?
</div>
<div class="input-group input-group-icon">
<input
name="pwd"
type="password"
class="form-control input-lg"
id="password"
/>
<span class="input-group-addon">
<span class="icon icon-lg">
<i class="fa fa-lock"></i>
</span>
</span>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox-custom checkbox-default">
<input
id="RememberMe"
name="rememberme"
type="checkbox"
/>
<label for="RememberMe">Remember Me</label>
</div>
</div>
<div class="col-sm-4 text-right">
<button
type="submit"
class="btn btn-primary hidden-xs"
id="signin"
>
Sign In
</button>
<button
type="submit"
class="btn btn-primary btn-block btn-lg visible-xs mt-lg"
id="signin1"
>
Sign In
</button>
</div>
</div>
<p class="text-center">
Don't have an account yet? Sign Up!
</p>
</form>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
// You can access a form by its name,
// for example if the form had the name 'form' you could access it through
// `const form = document.forms.form`
// in your case by using the same name id value should be accessed thus
const indexLogin = document.forms["index-login"];
indexLogin.addEventListener("submit", handleSubmit);
function handleSubmit(event) {
// Prevent submit form
event.preventDefault();
// Get data from inputs. Here this refer to the current form
const formData = new FormData(this);
// Inspect data collected
// for (const [key, value] of formData.entries()) {
// console.log(key, value);
// }
// Send form to php file
fetch("file.php", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(json => {
// do something
})
.catch(error => console.error(error.message));
}
But, your data will be visible through devtool in the network panel. I guess that will require another question.
I hope I have interpreted your question properly.

Related

How to convert HMAC_SHA256_MAC in PHP

index.php
<form class="row g-3" action="<?php echo base_url('signin'); ?>" method="post" id="loginForm" onsubmit="return hashpass();">
<div class="col-12">
<label for="inputUsername" class="form-label">Username</label>
<input type="text" class="form-control" name="uname" id="uname" placeholder="Enter Username" required>
</div>
<div class="col-12">
<label for="inputChoosePassword" class="form-label">Password</label>
<div class="input-group" id="show_hide_password">
<input type="password" class="form-control border-end-0" name="password" required id="password" value="12345678" placeholder="Enter Password"> <i class='bx bx-hide'></i>
</div>
</div>
<div class="col-12">
<div class="d-grid">
<button type="submit" id="signin" class="btn btn-primary" onclick="hashpass();"><i class="bx bxs-lock-open"></i>Sign in</button>
</div>
</div>
</form>
<script src="<?php echo base_url(); ?>/assets/js/HmacSHA256.js"></script>
<script>
function hashpass(){
var FormName='loginForm';
document.forms[FormName]["password"].value=HMAC_SHA256_MAC("aSm0$i_20eNh3os", document.forms[FormName]["password"].value);
return true;
}
</script>
Home_Controller.php
public function signin()
{
$userModel = new UserModel();
$uname = $this->request->getPost('uname');
$password = $this->request->getPost('password');
$data = $userModel->signin($uname);
foreach($data as $key=>$value)
{
$auth_id=$value->auth_id;
$s_password=$value->password;
}
if(!empty($data))
{
if(password_verify($password, $s_password))
{
$session->set('auth_id',$auth_id);
$this->response->redirect(base_url('dashboard'));
}else{
$this->response->redirect(base_url());
}
}
else
{
$this->response->redirect(base_url());
}
}
If I get value from front end suppose value is demo enter from front end then get in controller If I print $2y$10$nxdb2IIIu0QMcXH0T0q0buKcugSUNT3muDOmelBO.fjTE5D8OrICq. So now without this script I want $2y$10$nxdb2IIIu0QMcXH0T0q0buKcugSUNT3muDOmelBO.fjTE5D8OrICq this output using PHP function.
Here is the php exmple.
<?php
echo hash_hmac('sha256', 'data', 'secret');
?>
Update the JS script
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js"></script>
<script>
function hashpass(){
var FormName='loginForm';
document.forms[FormName]["password"].value=CryptoJS.HmacSHA256(document.forms[FormName]["password"].value, "aSm0$i_20eNh3os");
return true;
}
</script>
You can check the link.
Hash HMAC

ajax error checkUsn is not defined at HTMLInputElement.onkeyup

I am doing login form connected to a mysql database and I want to check if username is existing inside database without reloading the whole page. I am using Ajax for sending and receiving data from the server. Now I'm stuck with this error can
"checkUsn is not defined at HTMLInputElement.onkeyup". can someone help me with this? i've tried to google it but it seems my code is correct.
Here is my code
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
$('#status').html(response);
if (response == "OK"){
return: true;
}else{
return false;
}
}
});
}else{
$('#status').html("INCORRECT USN AND PW");
return false;
}
}
checkdata.php
<?php
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if(isset($_POST['emp_username'])){
$usn = $_POST['emp_username'];
$checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0){
echo "OK";
}else{
echo "Your Username not exist";
}
exit();
}
?>
here is my form
<form class="modal-content animate" action="/login_action.php" method="post" onsubmit="return checkall();">
<div class="container">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
<img class="avatar img-responsive col-lg-6 col-md-6 col-sm-6 col-xs-6" src="img/employee_avatar.png" alt="Avatar">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
</div>
<div class="container">
<label for="usn"><b>Username</b></label>
<input id="usn" type="text" placeholder="Enter Username" name="usn" onkeyup="checkUsn();" required>
<label for="pw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
<button type="button" onclick="btnClickTest()"> test </button>
<span id="status"> </span>
</form>
Thank you in Advance!
Hi guys I just got typo error on my code I write
return: true;
instead of
return true;
now my code is now working smoothly.
thanks
Try to change you success function like this :
success: function(response){
$('#status').html(response);
if (response == "succeed"){
return: true;
}else{
return false;
}
}

Redirect to controller codeigniter after checking validation

I validated my form Using AJAX
Here is my form
<p class="login-box-msg">
<?php
echo "<span id='error'>Sign in to start your session</span>";
?>
</p>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Employee ID" name="empid">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" name="pw">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-8">
<button type="button" class="btn btn-primary btn-block btn-flat" id="submit">Sign In</button>
</div>
<!-- /.col -->
</div>
</div>
<!-- /.login-box-body -->
<form>
Then I validated this using my ajax code
$("#submit").click(function(){
var form = $("form").serialize();
$.ajax({
url:'verify',
data: form,
dataType:'json',
type:'post',
success: function(e)
{
console.log(e.length);
if(e.length < 1)
{
$("#error").text("Invalid Login Credentials!");
$("#error").css("color","red");
setTimeout(function(){
$("#error").text("Sign in to start your session!");
$("#error").css("color","black");
},3000);
}
else
{
"What shoud I do"
// I tried $("form").submit() but it just repeat
//$("#submit").click(function())
}
}
});
On else bracket, I want to redirect to Controller on codeigniter called setCredentials() wherein it would set the credentials needed and redirect me to another page when the validation is completed (without error).
In else part enter the below code with the url you want to redirect to:
window.location = "<?php echo 'your/url'; ?>";

How to get a login form to accept a new registrant userid and password that was submitted successfully?

This is my first time asking a question on here in a long time so my formatting might be a little off.
My login form will not accept a new user registration that was submitted even though it shows the message that the form was submitted successfully. When I check the database through phpmyadmin, there is no record of the new registrant. My code is below.
index.php
<!-- Modal -->
<a href="#" class="modal" id="modal-one" aria-hidden="true">
</a>
<div class="modal-dialog">
<div class="modal-header">
×
</div>
<div class="modal-body">
<div id="content">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
<li class="active">LOGIN </li>
<li><label>/</label></li>
<li>SIGNUP</li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane active" id="red">
<form action="main.php" method="post" id="formID1" class="formular">
<span class="err"><?php if(isset($_GET['$message'])){ echo $_GET['$message'];} if(isset($_GET['loginerr'])){ echo $_GET['loginerr'];}if(isset($_GET['herr1'])){ echo $_GET['herr1'];} ?><br></span><br>
<div class="form-group">
<input type="text" placeholder="EMAIL ADDRESSS" name="email" class="validate[required,custom[email]] form-control" id="usr1" >
<span class="email"></span>
</div>
<div class="form-group">
<input type="password" placeholder="PASSWORD" name="password" class="validate[required] form-control" id="pwd1">
<span class="pass"></span>
</div>
<div class="form-group">
<input type="submit" id="submit1" name="login" class="submit1 btn btn-info" value="LOGIN">
</div>
<div class="modal-footer">
RESET YOUR PASSWORD
</div>
</form> </div>
<div class="tab-pane" id="orange">
<form action="main.php" method="post" id="formID2" class="formular">
<span class="err" id="a_err"><?php if(isset($_GET['$message'])){ echo $_GET['$message'];} ?><br></span><br>
<div class="form-group">
<input type="text" placeholder="EMAIL ADDRESSS" name="s_email" class="validate[required,custom[email]] form-control" id="usr2" >
<span class="email"></span>
</div>
<div class="form-group">
<input type="password" placeholder="PASSWORD" name="s_password" class="validate[required] form-control" id="spwd">
<span class="pass"></span>
</div>
<div class="form-group">
<input type="password" placeholder="CONFIRM PASSWORD" name="confirm_password" class="form-control validate[required,equals[spwd]]" id="cpwd">
<span class="rght"></span>
</div>
<div class="form-group">
<input type="submit" id="submit2" name="s_submit" class="submit2 btn btn-info" value="CREATE YOUR ACCOUNT">
</div>
<div class="modal-footer">
BY CREATING AN ACCOUNT YOU ACKNOWLEDGE THAT YOU
ACCEPT THE TERMS & CONDITIONS
</div>
</form>
</div>
</div>
</div>
</div>
</div>
sql file
CREATE TABLE IF NOT EXISTS `login` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`email` varchar(55) NOT NULL,
`password` varchar(55) NOT NULL,
`confirm_password` varchar(55) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
--
-- Dumping data for table `login`
--
INSERT INTO `login` (`id`, `email`, `password`, `confirm_password`)
validation.js
function signup_validation()
{
alert("helloooooooo");
var usr=document.getElementById("usr2").value;
alert($usr);
var pwd=document.getElementById("spwd").value;
var cpwd=document.getElementById("cpwd").value;
var atpos = usr.indexOf("#");
var dotpos = usr.lastIndexOf(".");
if(usr=="" || pwd=="" || cpwd=="" || pwd!=cpwd)
{
document.getElementById("a_err").innerHTML="Please Fill All Fields";
if(usr==""){
document.getElementById("a_err").innerHTML="Please Enter User Name";
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=usr.length) {
document.getElementById("js_error").innerHTML="Not a valid e-mail address";
}
else if(pwd==""){
document.getElementById("a_err").innerHTML="Please Enter Email";
}
else if(cpwd==""){
document.getElementById("a_err").innerHTML="Please Re-Enter password ";
}
else if(pwd!=cpwd){
document.getElementById("a_err").innerHTML="Password Do Not Match";
}
return false;
}
else{
document.getElementById("a_err").innerHTML="";
return true;
}
}
function login_validation()
{
var username=document.getElementById("usr1").value;
//alert(username);
var atpos1 = username.indexOf("#");
var dotpos1 = username.lastIndexOf(".");
var password=document.getElementById("pwd1").value;
if(username=="" || password=="")
{
document.getElementById("js_error1").innerHTML="Please Fill All Fields";
if(username==""){
document.getElementById("js_error1").innerHTML="Please Enter Your Email Id";
}
else if (atpos1<1 || dotpos1<atpos1+2 || dotpos1+2>=username.length) {
document.getElementById("js_error1").innerHTML="Not a valid e-mail address";
}
else if(password==""){
document.getElementById("js_error1").innerHTML="Please Enter Password.";
}
return false;
}
else{
document.getElementById("js_error1").innerHTML="";
return true;
}
}
main.php
<?php
include 'config.php';
session_start();
//echo "hii";
if(isset($_POST['s_submit'])){
$email=$_POST['s_email'];
//echo $email;
$pass=$_POST['s_password'];
$sql=mysqli_query($con,"INSERT INTO personal_info (`email`,`password`,`first_time_login`)VALUES('".$email."','".$pass."','0')");
header('location:index.php?$message="form successfully submitted you can login"');
}
if(isset($_POST['login'])){
$email=$_POST['email'];
$pass=$_POST['password'];
$q=mysqli_query($con,"SELECT * FROM personal_info WHERE email='".$email."' AND password='".$pass."' ");
$row_fetch=mysqli_fetch_assoc($q);
echo $row_fetch['first_name'];
$count=mysqli_num_rows($q);
if($count>0){
$id=$row_fetch['id'];
$_SESSION['id']=$id;
//$id=mysqli_insert_id($conn);
if($row_fetch['first_time_login']=="1")
{
header('location:index.php#');
}
else{
header('location:user.php');
}
}
else{
header('location:index.php?loginerr="invalid user"');
}
}
mysqli_close($con);
?>
Your <form action="" method="post" id="formID2" class="formular"> particularly the action part must have the php file on where your post code is located at (if the php code is located on a separate file)
Example:
<form action="main.php" method="post" id="formID2" class="formular">
or
<form action="your_file_name.php" method="post" id="formID2" class="formular">

Alert box does not work

I am trying to display an alert box and click on Ok to refresh the page. I have tried using window.location.reload(true)
I want to show a message before page reload. The problem is that the page reloads automatic but the alert box not showing.
HTML Content
<form action="<?php echo $action_link; ?>" method="post" name="form_Change_Password" id="form_Change_Password" class="form-horizontal" novalidate="novalidate">
<input type="hidden" name="id" value="<?php echo $admin_id; ?>">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button> You have some form errors. Please check below.
</div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button> Your form validation is successful!
</div>
<div class="form-group margin-top-20">
<label class="control-label col-md-3">Old Password
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="password" class="form-control" name="old_password" id="old_password" value="">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">New Password
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="password" class="form-control" name="new_password" id="new_password" value="">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Confirm Password
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="password" class="form-control" name="confirm_password" id="confirm_password" value="">
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="button" class="btn green" name="btnChangePassword" onclick="newpassword(<?php echo $admin_id; ?>)">Update</button>
Cancel
</div>
</div>
</div>
</form>
Ajax Code:
$.ajax({
url: "<?php echo $action_link; ?>",
type: "POST",
data: {
'id': <?php echo $admin_id; ?>,
'old_pass': old_pass,
'new_pass': new_pass,
'conf_pass': conf_pass,
change_password : 'change_password'
},
success: function (result){
if(result == 1){
bootbox.alert('Password changed successfully.');
window.location.reload(true);
}else if(result == 2){
bootbox.alert('New password and confirm password does not match.');
return false;
}
else if(result == 0){
bootbox.alert('Old password does not match.');
}
},
error: function (result){
}
});
Action
if(isset($_REQUEST['change_password']) && $_REQUEST['change_password'] == 'change_password'){
ob_get_clean();
$id = $_REQUEST['id'];
$password = mysqli_real_escape_string($obj->CONN,md5($_REQUEST['old_pass']));
$dbpassword = $admin->select_password($id);
$newpass = $_REQUEST['new_pass'];
$confpass = $_REQUEST['conf_pass'];
if($dbpassword != $password){
echo 0; exit;
}elseif($newpass != $confpass){
echo 2; exit;
}
else{
$admin->update_password($id, md5($newpass), $current_date);
echo 1; exit;
}
}
You have to use bootbox callback :
bootbox.alert("Password changed successfully.", function() {
// any code you want to happen after the alert is dismissed
window.location.reload(true);
});
So it will be :
...
success: function (result){
if(result == 1){
bootbox.alert("Password changed successfully.", function() {
window.location.reload(true);
});
}else if(result == 2){
bootbox.alert("New password and confirm password does not match.", function() {
return false;
});
}else if(result == 0){
bootbox.alert('Old password does not match.');
}
},
...
Hope this helps.
Try using the following:
bootbox.alert('Password changed successfully.', function(){
window.location.reload(true);
});
Instead of:
bootbox.alert('Password changed successfully.');
window.location.reload(true);

Categories

Resources