How create an url dynamically in Jquery AJAX? - php

I have a reset password system in PHP.
First - the forgot password.php sends to the customer an email with a link to reset the password.
This one is composed of the email of the customer and a unique key code for resetting the password
this email is like :
Please click the following link to reset your password: .../resetpassword.php?email=pm.chaumien#me.com&code=5e1b876bb1e36
On this page... you have a form with 2 boxes for a new password.
<?php
include 'main.php';
// Output message
$email=$_GET['email'];
$code=$_GET['code'];
$msg = '';
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if (isset($_GET['email'], $_GET['code']) && !empty($_GET['code'])) {
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
$stmt = $pdo->prepare('SELECT * FROM accounts WHERE email = ? AND reset = ?');
$stmt->execute([$_GET['email'], $_GET['code']]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// If the account exists with the email and code
if ($account) {
if (isset($_POST['npassword'], $_POST['cpassword'])) {
if (strlen($_POST['npassword']) > 20 || strlen($_POST['npassword']) < 5) {
$msg = 'Password must be between 5 and 20 characters long!';
} else if ($_POST['npassword'] != $_POST['cpassword']) {
$msg = 'Passwords must match!';
} else {
$stmt = $pdo->prepare('UPDATE accounts SET password = ?, reset = "" WHERE email = ?');
// We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
$password = password_hash($_POST['npassword'], PASSWORD_DEFAULT);
$stmt->execute([$password, $_GET['email']]);
$msg = 'Password has been reset! You can now login!';
}
}
} else {
die('Incorrect email and/or code!');
}
} else {
die('Please provide the email and code!');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body id="register_bg">
<nav id="menu" class="fake_menu"></nav>
<div id="preloader">
<div data-loader="circle-side"></div>
</div>
<!-- End Preload -->
<div class="rsvp-form" id="login">
<aside>
<figure>
<img src="../img/logoBlack.png" width="64" height="64" data-retina="true" alt="" class="logo_sticky">
</figure>
<?php echo 'email='.$email.'&'.'code='.$code?>
<form action="resetpassword.php?email=<?=$_GET['email']?>&code=<?=$_GET['code']?" method="post">
<div class="form-group">
<label>Your password</label>
<input class="form-control" type="password" name="npassword" id="npassword">
<i class="icon_lock_alt"></i>
</div>
<div class="form-group">
<label>Confirm password</label>
<input class="form-control" type="password" name="cpassword" id="cpassword">
<i class="icon_lock_alt"></i>
</div>
<!-- Do Not Remove! -->
<p class="error"></p>
<p class="message"></p>
<!-- Do Not Remove! Ends! -->
<div id="pass-info" class="clearfix"></div>
<div class="text-right"><button type="submit" class="btn_1 rounded full-width add_top_30">Reset Password</button></div>
</form>
<!-- COMMON SCRIPTS -->
<script src="../js/jquery-2.2.4.min.js"></script>
<script src="../js/common_scripts.js"></script>
<script src="../js/main.js"></script>
<script src="../assets/validate.js"></script>
<script src="../assets/formreset.js"></script>
<!-- SPECIFIC SCRIPTS -->
<script src="../assets/pw_strenghtreset.js"></script>
</body>
For check this form I've a jquery with AJAX for the form action and the verification but on this one, it doesn't work.
$('.rsvp-form form').submit(function(event) {
var $password = $(this).find('input[id="npassword"]');
var $password1 = $(this).find('input[id="cpassword"]');
$('.rsvp-form p.error').show();
$('input[id="npassword"],input[id="cpassword"]').removeClass('error');
if ($password.val() === '') {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> Veuillez saisir un mot de passe, svp !');
$password.addClass('error').focus();
return false;
}
if ($password1.val() === '') {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> Veuillez saisir un mot de passe, svp !');
$password1.addClass('error').focus();
return false;
}
if ($password1.val() != $password.val()) {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> les mots de passe ne correspondent pas !');
$password1.addClass('error').focus();
return false;
}
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find('input, button, textarea');
var serializedData = $form.serialize();
$inputs.prop('disabled', true);
request = $.ajax({
url: 'resetpassword.php?email=<?php echo $email; ?>&code=<?php echo $code; ?>',
type: 'post',
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
$('.rsvp-form p.error').hide();
$('.rsvp-form p.message').html('success, password was changed').fadeOut(10000);
$('.rsvp-form form').find('input[type=text], textarea, select').val('');
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
'The following error occured: '+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop('disabled', false);
});
event.preventDefault();
});
});

Related

PHP response under form in html

I would like to write a communicate during registration, when user already exists. With this code it redirects me on another page. I would like to see this communicate under form. I tried like this but it still redirects me on another page. I also would like to do by function 'response', but it didn't work.
register3.php
<html>
<?php
if (isset($_POST["register"])) {
$connection = new mysqli("localhost", "root", "root", "users");
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$imie = $connection->real_escape_string($_POST["imie"]);
$nazwisko = $connection->real_escape_string($_POST["nazwisko"]);
$data2 = $connection->query("SELECT * FROM user WHERE email='$email'");
if($data2->num_rows >0) {
exit('<font color="red">This user already exists</font>');
} else
$data = $connection->query("INSERT INTO user
(email, password, imie, nazwisko)
VALUES ('$email', '$password', '$imie', '$nazwisko')");
if (($data === false) && ($email != "" || $password != "")) {
echo '<script>alert("Wypełnij poprawnie pola!")</script>';
} else {
echo '<script>alert("Zostałeś zarejestrowany, zaloguj się.")</script>';
}
}
?>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-16">
<link rel="stylesheet" href="style_reg.css">
<title>Strona o nalewkach - Login </title>
</head>
<body>
<nav class="navbar">
<div class="content">
<div class="logo" >Nalewki z tradycją</div>
<ul class="menu-list">
<div class="icon cancel-btn">
<i class="fas fa-times"></i>
</div>
<li>Home</li>
<li>Przepisy na nalewki</li>
<li>Logowanie</li>
<li>Galeria</li>
<li>Kontakt</li>
</ul>
<div class="icon menu-btn">
<i class="fas fa-bars"></i>
</div>
</div>
</nav>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-50">
<form class="login100-form validate-form" method="POST" action="register3.php">
<span class="login100-form-title p-b-33">
Zarejestruj się do świata nalewek
</span>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="text" name="email" placeholder="Email">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="password" name="password" placeholder="Haslo">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="text" name="imie" placeholder="Imie">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="text" name="nazwisko" placeholder="nazwisko">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="container-login100-form-btn m-t-20">
<input type="submit" class="login100-form-btn" value="Zarejestruj" name="register">
</div>
<p id="response"></p>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('Wypelnij poprawnie formularz');
else {
$.ajax({
url: 'register3.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password,
imiePHP: imie,
nazwiskoPHP: nazwisko
},
success: function(response) {
$("#response").html(response);
if (response.indexOf('success') >=0)
alert('Wypelnij poprawnie formularz');
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>
You use jQuery but you never import it, put this in hour head section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In your javascript you have this
$("#login").on('click', function () {
but I don't see any element with id login. To prevent form submition just jsut replace the above line with this
$("form").on('submit', function (e) {
e.preventDefault();
Give each of your form inputs an id, they don't have them now, so as to be able to do that
var email = $("#email").val();
var password = $("#password").val();
var imie = $("#imie").val();
var nazwisko = $("#nazwisko").val();
Prepare separate php file for your ajax call, can't use same register3.php for that, because php file has to be executed to give you a response, you cannot do that on register3.php without page reload.
In that other php file, for example email-check.php, check if user exists and if not register and return response ok
$.ajax({
url: 'email-check.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password,
imiePHP: imie,
nazwiskoPHP: nazwisko
},
success: function(response) {
if (response == 'ok') {
//new user registered succesfully
//log user in or redirect to login page
} else {
//user already exists
$("#response").html('This email address is taken');
},
});

can't get input type text via js

i bought course in Udemy to make login system and just wanted to add more input in html to get username ..... but it didn't work
it took me like 15 hours and still can't understand why it don't work
<div class="uk-section uk-container">
<div class="uk-grid uk-child-width-1-3#s uk-child-width-1-1" uk-grid>
<form class="uk-form-stacked js-register">
<h2>Register</h2>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Username</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="text" required='required' placeholder="Username">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Email</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="email" required='required' placeholder="email#email.com">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Passphrase</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="password" required='required' placeholder="Your passphrase">
</div>
</div>
<div class="uk-margin uk-alert uk-alert-danger js-error" style='display: none;'></div>
<div class="uk-margin">
<button class="uk-button uk-button-default" type="submit">Register</button>
</div>
</form>
</div>
jquery code:
$(document).on("submit", "form.js-register", function(event) {
event.preventDefault();
var _form = $(this);
var _error = $(".js-error", _form);
var dataObj = {
username: $("input[type='text']", _form).val(),
email: $("input[type='email']", _form).val(),
password: $("input[type='password']", _form).val()
};
if(dataObj.email.length < 6) {
_error
.text("Please enter a valid email address")
.show();
return false;
} else if (dataObj.password.length < 11) {
_error
.text("Please enter a passphrase that is at least 11 characters long.")
.show();
return false;
}
// Assuming the code gets this far, we can start the ajax process
_error.hide();
$.ajax({
type: 'POST',
url: '/ajax/register.php',
data: dataObj,
dataType: 'json',
async: true,
})
.done(function ajaxDone(data) {
// Whatever data is
if(data.redirect !== undefined) {
window.location = data.redirect;
} else if(data.error !== undefined) {
_error
.text(data.error)
.show();
}
})
.fail(function ajaxFailed(e) {
// This failed
})
.always(function ajaxAlwaysDoThis(data) {
// Always do
console.log('Always');
})
return false;
})
php code :
define('__CONFIG__', true);
// Require the config
require_once "../inc/config.php";
if($_SERVER['REQUEST_METHOD'] == 'POST' or 1==1) {
// Always return JSON format
// header('Content-Type: application/json');
$return = [];
$email = Filter::String( $_POST['email'] );
// Make sure the user does not exist.
$findUser = $con->prepare("SELECT user_id FROM users WHERE email = LOWER(:email) LIMIT 1");
$findUser->bindParam(':email', $email, PDO::PARAM_STR);
$findUser->execute();
if($findUser->rowCount() == 1) {
// User exists
// We can also check to see if they are able to log in.
$return['error'] = "You already have an account";
$return['is_logged_in'] = false;
} else {
// User does not exist, add them now.
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$username = $_POST['text'] ;
$addUser = $con->prepare("INSERT INTO users(username,email, password) VALUES(:username,LOWER(:email), :password)");
$addUser->bindParam(':username', $username, PDO::PARAM_STR);
$addUser->bindParam(':email', $email, PDO::PARAM_STR);
$addUser->bindParam(':password', $password, PDO::PARAM_STR);
$addUser->execute();
$user_id = $con->lastInsertId();
$_SESSION['user_id'] = (int) $user_id;
$return['redirect'] = '/dashboard.php?message=welcome';
$return['is_logged_in'] = true;
}
echo json_encode($return, JSON_PRETTY_PRINT); exit;
} else {
// Die. Kill the script. Redirect the user. Do something regardless.
exit('Invalid URL');
}
what happen that email and password send to database (which i get from source code of the course)
and username which i added just don't do anything .. prevent page from redirect
i really think i made an idiot mistake but i think 15 hours for trying is enough too .. forgive me for that .. and for my bad English
Thanks
edit this in html
<div class="uk-form-controls">
<input class="uk-input" name="username" type="text" required='required' placeholder="Username">
</div>
and edit dataobj in ajax
var dataObj = {
username: $("input[name='username']", _form).val(),
email: $("input[type='email']", _form).val(),
password: $("input[type='password']", _form).val()
};
and remove all the id's from html because you have define the same id for every html tag(username, email, paddword), javascript will throw an error if more than one html tag have the same id

How to stay on same page after login

I am building an event registration system which displays event registration list if the user is logged in without page refresh using Ajax. However, when I try to login I get undefined index name on line echo "Hello ".$_SESSION["name"]."<br/>"; in index.php. My code is:-
index.php:-
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Registration</title>
<link href="style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<div id="wrapper">
<!--Login div-->
<div id="logincontainer">
<form id="loginform" method="post">
<h3>Login</h3>
<div class="display-error" style="display: none;"></div>
<input type="email" name="lemail" placeholder="Enter email address" required>
<input type="password" name="lpassword" placeholder="Enter password" required>
<input type="submit" value="Sign In">
<p>Forgot Password</p>
<p id="bottom">Don't have an account yet? Sign up</p>
</form>
</div>
<div id="signupcontainer">
<form id="registerform" method="post">
<h3>Register</h3>
<div class="display-error" style="display: none;"></div>
<input type="text" name="rname" placeholder="Full Name" required>
<input type="email" name="remail" placeholder="Enter valid email" required>
<input type="password" name="rpassword" placeholder="Password" required>
<input type="text" name="rmobile" maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" required>
<input type="submit" value="Create Account">
<p id="bottom">Already have an account? Sign In</p>
</form>
</div>
<!--Testing refresh portion-->
<div id="after-login" style="display: none;">
<?php
echo "Hello ".$_SESSION["name"]."<br/>";
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
<!--Testing portion ends-->
</div>
<script>
$(document).ready(function(){
$("#loginform").submit(function(){
var data = $("#loginform").serialize();
checkRecords(data);
return false;
});
function checkRecords(data){
$.ajax({
url : 'loginprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(){
alert("Email/Password is Incorrect");
}
});
}
});
</script>
<!--Signup Ajax-->
<script>
$(document).ready(function(){
$("#registerform").submit(function(){
var data = $("#registerform").serialize();
signupRecords(data);
return false;
});
function signupRecords(data){
$.ajax({
url : 'signupprocess.php',
data : data,
type : 'POST',
dataType : 'json',
success: function(data){
if(data.code == 200){
alert('You have successfully Signed Up \n Please Login now.');
setTimeout(function(){
location.reload();
},500);
}
else{
$(".display-error").html("<ul>"+data.msg+"</ul");
$(".display-error").css("display","block");
}
},
error: function(jqXHR,exception){
console.log(jqXHR);
}
});
}
});
</script>
</body>
loginprocess.php
<?php
ob_start();
session_start();
require_once('dbconnect.php');
require_once('function.php');
$errorMsg = "";
$email = trim($_POST["lemail"]);
$password = trim($_POST["lpassword"]);
if(empty($email)){
$errorMsg .= "<li>Email is required</li>";
}
else{
$email = filterEmail($email);
if($email == FALSE){
$errorMsg .= "<li>Invalid Email Format</li>";
}
}
if(empty($password)){
$errorMsg .= "<li>Password Required.</li>";
}
else{
$password = $password;
}
if(empty($errorMsg)){
$query = $db->prepare("SELECT password from users WHERE email = ?");
$query->execute(array($email));
$pwd = $query->fetchColumn();
if(password_verify($password, $pwd)){
$_SESSION['email'] = $email;
//Testing piece
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email']]);
exit;
}
else{
json_encode(['code'=>400, 'msg'=>'Invalid Email/Password']);
exit;
}
}
else{
echo json_encode(['code'=>404, 'msg'=>$errorMsg]);
}
?>
As far as I can see the problem is that after login call you DO NOT reload the #after-login container contents - you only show it.
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#logincontainer").hide();
$("#after-login").show();
}
In the other words the #after-login contents only load on the first page load (before login) and then are not updated by your ajax call (only then you would have access to $_SESSION["name"]).
IMHO proper solution would be to return the $_SESSION["name"] value in the loginprocess.php response and update it in the #after-login container before showing it (eg. use an empty span where the name should appear which you'll fill out on login).
//Something like
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("span#name_placeholder").text(data.name) //return name from loginprocess.php
$("#logincontainer").hide();
$("#after-login").show();
}
The best solution would to be to create a html element like this for the
<div id="after-login" style="display: none;">
<h5 id="Username"></h5>
<?php
echo '<span class="glyphicon glyphicon-logout"></span>Sign Out<br/>';
?>
<form id="events" method="post">
Code Ardor<input type="checkbox" name="coding[]" value="ardor">
Designophy<input type="checkbox" name="coding[]" value="design"><br>
<input type="submit" value="Submit" name="submit-btn">
</form>
</div>
then after this include the username in the json like this
$qry = $db->prepare("SELECT name from users WHERE email = ?");
$qry->execute(array($email));
$nme = $qry->fetchColumn();
//$_SESSION['name']=$nme;
//Testing code ends
echo json_encode(['code'=>200, 'email'=>$_SESSION['email'],'username'=>$nme]);
exit;
on the ajax call you can now access the json response with the username included and feed the span element with the username like this
if(data.code == 200){
//alert('You have successfully logged in');
//window.location='dashboard.php';
$("#username").test(data.username);
$("#logincontainer").hide();
$("#after-login").show();
}

The Enter button not working on Login page

I just made a login system but I can only login with pressing the button on my screen, not using the enter button on my keyboard. How can I enable this? I read something about the AcceptButton, but how do I apply this?
my code:
login.php
<?php
require('inc/functions.php');
session_start();
if(checkLogedIn()){
header("location:index.php");
die();
}
include 'inc/header.php'
?>
<body>
<div id="wrap">
<div class="text-center">
<img src="img/logo.png" height="125" width="125">
</div>
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">Inloggen</div>
<div class="result"></div>
<div class="panel-body">
<form role="form" id="loginForm">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Gebruikersnaam" name="username" type="text" autofocus="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Wachtwoord" name="password" type="password">
</div>
<div class="row">
<div class="col-xs-7">
Inloggen
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div><!-- /.col-->
</div><!-- /.row -->
</div>
<footer class="footer">
<div class="text-center">
<p class="text-muted">© <?php echo date("Y"); ?> company name</p>
</div>
</footer>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('.result').hide();
$(".post").on("click",function(){
// console.log('clicked!');
var formData = $('#loginForm').serialize();
$.ajax({
type: "POST",
url: "checkauth.php",
data: $("#loginForm").serialize(), // serializes the form's elements.
success: function(data){
//window.location.href = "/welcome";
// console.log(data);
if(data.status2 == 'success'){
//
$('.panel-body').fadeOut(1400);
$('.result').html(data.message);
$('.result').fadeIn(1200);
window.setTimeout(function() {
window.location.href = 'index.php';
}, 2000);
}else {
$('.result').html(data.message);
}
}
});
});
});
</script>
</body>
</html>
checkauth.php
<?php
session_start();
/* Check Login form submitted */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Content-Type: application/json');
/* Define username and associated password array */
$logins = array('admin' => 'admin2',
'username1' => 'password1',
'username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['username']) ? $_POST['username'] : '';
$Password = isset($_POST['password']) ? $_POST['password'] : '';
// print_r($_POST);
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
$_SESSION['UserData']['loggedin']=TRUE;
$return['message'] = '<br><div class="alert alert-success" role="alert">Login gegevens correct, welkom!</div><br>';
$return['status2'] = 'success';
} else {
/*Unsuccessful attempt: Set error message */
$return['message'] = '<div class="alert alert-danger" role="alert">Incorrecte login gegevens. Probeer het aub. opnieuw.</div>';
$return['status2'] = 'error';
}
echo json_encode($return);
}
else{
exit('No direct acces to this script!');
}
?>
Can anyone help ?
To make enter button to work you can use
<input type="submit">
Rather then
Inloggen
You can trigger the click on enter:
$(document).keydown(function(e){
var c = e.which;
e.stopPropagation();
if(c==13){
e.preventDefault();
$(".post").trigger("click");
}
});
You can modify your click as:
$('#loginForm').keypress(function (e) {
if(e.keyCode=='13') //Keycode for "Return"
$('#login').click();
}});

How to submit a form with ajax and php

I am trying to add a change password function on my site. I decided that i would try using ajax so the site does not have to update itself. But i have one problem. When i submit the form to my PHP file nothing happends i just get the success from the ajax file. And the password is not change in my SQL db.
This is the html file.
<div class="boxPW">
<div class="boxInner">
<img class="closeBox" style="float: right;" src="images2/zoom/closebox.png" />
<h2>Endre passord ditt</h2>
<div id="lineBreak" style="margin-top: -19px; width: 70%;"></div>
<h4>Skriv inn et nytt passord for <?php echo $fname.' '.$lname.' ';?>
Vi anbefaler at du oppretter et unikt passord –
et du ikke bruker på noen andre nettsteder. <h4>
<div class="boxInner2">
<form id="changePw" name="changePw" method="POST" action="">
<input type="password" id="oldPw" name="oldPw" placeholder="Nåværende passord" />
<label id="error_oldPw" class="error">Fyll inn nåværende passord</label>
<p style="margin: 0; width:100px; font-size:9px; color: #38C6DA; ">Glemt ditt passord?</p>
<div class="divider"></div>
<input type="password" id="newPw" name="newPw" placeholder="Nytt passord"/>
<label id="error_newPw" class="error">Fyll inn nytt passord</label>
<div class="divider"></div>
<input type="password" id="conNewPw" name="conNewPw" placeholder="Bekreft nytt passord"/>
<label id="error_conNewPw" class="error">Gjenta ditt passord</label>
<div class="divider"></div>
<input id="buttonpw" class="button" type="button" name="submit" value="Endre passord" />
</form>
</div>
</div>
</div>
And here are my Jquery file (returnPwBox.js)
$(document).ready(function() {
$('.error').hide();
$('#buttonpw').click(function(){
//Validate inputData
$('error').hide();
var oldPw = $("input#oldPw").val();
if(oldPw == ""){
$("label#error_oldPw").show();
$("input#oldPw").focus();
return false;
}
var newPw = $("input#newPw").val();
if(newPw == ""){
$("label#error_newPw").show();
$("input#newPw").focus();
return false;
}
var conNewPw = $("input#conNewPw").val();
if(conNewPw != newPw){
$("label#error_conNewPw").show();
$("input#conNewPw").focus();
return false;
}
var dataString = 'oldpw='+ oldPw + '&newPw=' + newPw + '&conNewPw=' + conNewPw;
$.ajax({
type: "POST",
url: "changePw.php",
data: dataString,
success: function(){
$('.boxInner2').html("<div id='message' style='width: 300px;'></div");
$('#message').html("<h2>Endring fullført</h2>")
.append("<h4>Ditt passord er nå endret</h44>")
.hide()
.fadeIn(1000, function(){
$('#message').append("<img id='checkmark' src='imgaes2/pitcharrow.gif'/>");
});
}
});
return false;
});
And here are my changePw.php:
<?php
include('conn.php');
require_once('auth.php');
include('fetchMemData.php');
function clean($str){
$str=#trim($str);
if(get_magic_quotes_gpc());{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$id=$_SESSION['SESS_MEMBER_ID'];
$oldPw = clean($_POST['oldPw']);
$newPw = clean($_POST['newPw']);
$conNewPw = clean($_POST['conNewPw']);
$oldPw = strip_tags($oldPw);
$newPw = strip_tags($newPw);
$conNewPw = strip_tags($conNewPw);
$oldPw = md5($oldPw);
$newPw = md5($newPw);
$conNewPw = md5($conNewPw);
if($oldPw == $password)
{
mysql_query("UPDATE reguser SET password='$newPw' WHERE mem_id='$id'");
}else{
echo ("Feil nåværende passord");
}
?>
If anyone see any errors or any suggestions, shout out! I need some help:)
Based on the code you wrote $password value is not asigned (unless you did it in another file) therefore $password is NULL , and the if:
if($oldPw == $password)
{
mysql_query("UPDATE reguser SET password='$newPw' WHERE mem_id='$id'");
}else{
echo ("Feil nåværende passord");
}
returns false

Categories