I think i need someone with a better eye to help me spot my error. I am trying to change the current password without refreshing the page. I get the error message "Error, please try again!". This is my code so far.
HTML
<form name="resetform" action="changepass.php" id="resetform" class="passform" method="post" role="form">
<h3>Change Your Password</h3>
<br />
<input type="hidden" name="username" value="<?php echo $sname;?>" ></input>
<label>Enter Old Password</label>
<input type="password" class="form-control" name="old_password" id="old_password">
<label>Enter New Password</label>
<input type="password" class="form-control" name="new_password" id="new_password">
<label>Confirm New Password</label>
<input type="password" class="form-control" name="con_newpassword" id="con_newpassword" />
<br>
<input type="submit" class="btn btn-warning" name="password_change" id="submit_btn" value="Change Password" />
</form>
PHP
<?php
include_once 'database-config.php';
if (isset($_POST['password_change'])) {
$username = strip_tags($_POST['sname']);
$password = strip_tags($_POST['old_password']);
$newpassword = strip_tags($_POST['new_password']);
$confirmnewpassword = strip_tags($_POST['con_newpassword']);
// match username with the username in the database
$sql = "SELECT * FROM users WHERE username='$sname'";
$query = $dbh->prepare($sql);
$query->execute();
$row = $query->fetchAll();
$hash = $row[0]["password"];
//$hash = $results[0]["password"];
if ($password == $hash){
if($newpassword == $confirmnewpassword) {
$sql = "UPDATE users SET password = '$newpassword' WHERE username = '$username'";
$query = $dbh->prepare($sql);
$query->execute();
echo "Password Changed Successfully!";
} else echo "Passwords do not match!";
}
} else echo "Please type your current password accurately!";
}
?>
Jquery
<script type="text/javascript">
$(document).ready(function() {
var frm = $('#resetform');
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function(data){
$('#success').html("<div id='message'></div>");
$('#message').html("<h2>Password changed successfully!</h2>")
.delay(3000).fadeOut(3000);
},
error: function(data) {
$('#error').html("<div id='errorMessage'></div>");
$('#errorMessage').html("<h3>Error, please try again!</h3>")
.delay(2000).fadeOut(2000);
}
});
e.preventDefault();
});
});
</script>
i would appreciate any corrections :-)
There are several issues with your code, such as:
See this statement here,
if (isset($_POST['password_change'])) { ...
Here, $_POST['password_change']
is not set becacuse jQuery's serialize()
does not include encoding buttons or submit inputs, so you have to append the name and value of the submit button to your result, like this:
var formData = frm.serialize();
formData += '&' + $('#submit_btn').attr('name') + '=' + $('#submit_btn').attr('value');
The variable $username
is not set because of this statement,
$username = strip_tags($_POST['sname']);
It should be,
$username = strip_tags($_POST['username']);
There's no point creating an element inside another element to display the success/error message, and also the message would be same irrespective of the outcome of the query. Plus you're not making use of server's response data
. See these following callback functions in your AJAX request,
success: function(data){
$('#success').html("<div id='message'></div>");
$('#message').html("<h2>Password changed successfully!</h2>")
.delay(3000).fadeOut(3000);
},
error: function(data) {
$('#error').html("<div id='errorMessage'></div>");
$('#errorMessage').html("<h3>Error, please try again!</h3>")
.delay(2000).fadeOut(2000);
}
Instead, make a div
element like this:
<div id="message"></div>
And display the success/error message in your callback functions like this:
success: function(data){
$('#message').html(data).delay(3000).fadeOut(3000);
},
error: function(jqXHR, textStatus, errorThrown) {
$('#message').html(textStatus).delay(2000).fadeOut(2000);
}
There are few syntax errors comprising of Parse error: syntax error, unexpected '}' in ...
in your PHP code.
Always prepare, bind and execute your queries to prevent any kind of SQL injection. And this is how you can prevent SQL injection in PHP.
Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
So your code should be like this:
HTML:
<form name="resetform" action="changepass.php" id="resetform" class="passform" method="post" role="form">
<h3>Change Your Password</h3>
<br />
<input type="hidden" name="username" value="<?php echo $sname; ?>" ></input>
<label>Enter Old Password</label>
<input type="password" class="form-control" name="old_password" id="old_password">
<label>Enter New Password</label>
<input type="password" class="form-control" name="new_password" id="new_password">
<label>Confirm New Password</label>
<input type="password" class="form-control" name="con_newpassword" id="con_newpassword" />
<br>
<input type="submit" class="btn btn-warning" name="password_change" id="submit_btn" value="Change Password" />
</form>
<!--display success/error message-->
<div id="message"></div>
jQuery:
$(document).ready(function() {
var frm = $('#resetform');
frm.submit(function(e){
e.preventDefault();
var formData = frm.serialize();
formData += '&' + $('#submit_btn').attr('name') + '=' + $('#submit_btn').attr('value');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
success: function(data){
$('#message').html(data).delay(3000).fadeOut(3000);
},
error: function(jqXHR, textStatus, errorThrown) {
$('#message').html(textStatus).delay(2000).fadeOut(2000);
}
});
});
});
PHP:
<?php
include_once 'database-config.php';
if (isset($_POST['password_change'])) {
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['old_password']);
$newpassword = strip_tags($_POST['new_password']);
$confirmnewpassword = strip_tags($_POST['con_newpassword']);
// match username with the username in the database
$sql = "SELECT * FROM `users` WHERE `username` = ? LIMIT 1";
$query = $dbh->prepare($sql);
$query->bindParam(1, $username, PDO::PARAM_STR);
if($query->execute() && $query->rowCount()){
$hash = $query->fetch();
if ($password == $hash['password']){
if($newpassword == $confirmnewpassword) {
$sql = "UPDATE `users` SET `password` = ? WHERE `username` = ?";
$query = $dbh->prepare($sql);
$query->bindParam(1, $newpassword, PDO::PARAM_STR);
$query->bindParam(2, $username, PDO::PARAM_STR);
if($query->execute()){
echo "Password Changed Successfully!";
}else{
echo "Password could not be updated";
}
} else {
echo "Passwords do not match!";
}
}else{
echo "Please type your current password accurately!";
}
}else{
echo "Incorrect username";
}
}
?>
Change here
$username = strip_tags($_POST['username']);//not sname
Your form is not submitting because jQuery's .serialize()
does not include the value in input type=submit
therefore PHP's if (isset($_POST['password_change'])) {
fails.
Check this out: jQuery serializeArray doesn't include the submit button that was clicked
I would also include better error handling in your AJAX. Try something like this:
$.ajax({
type: "post",
url: "",
success: function (data) {
//...
},
error: function (request, status, error) {
console.log(request);
console.log(status);
console.log(error);
}
});