我试图在我的网站中实现密码更改功能。我已经完成了所有密码更改脚本,验证等。但现在我需要阻止页面进入脚本页面或刷新。当用户点击提交按钮时,除了显示successfully changed
或error
的消息,我不想更改。因此,这里是我的html:
AJAX密码更改不刷新
<form id="change_Pass" action="" method="post">
Current Password<input type="password" id="change_password" name="change_password"><br>
New Password<input type="password" id="new_password" name="new_password"><br>
Verify Password<input type="password" id="verify_password" name="verify_password"><br>
<input type="submit" value="Submit" id="change_pass_submit">
</form>
而且我的jquery:
$('#change_pass_submit').click(function(){
var $this = $(this);
$.ajax({
data: $this.serialize(), // get the form data
type: "POST", // GET or POST
url: "/Private/change_password.php", // the file to call
success: function() { // on success..
//$('#success_div).html(response); // update the DIV
alert("good");
},
error: function() { // on error..
//$('#error_div).html(e); // update the DIV
alert("bad");
}
});
return false; //so it doesn't refresh when submitting the page
});
而且我的PHP:
<?php
session_start();
require_once '../classes/Bcrypt.php';
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$usr = $_SESSION["username"];
$old_pwd = $_POST["change_password"];
$new_pwd = $_POST["new_password"];
$new_pwd = Bcrypt::hash($new_pwd);
try {
$link = new PDO('mysql:host=*;dbname=*;charset=UTF-8','*','*');
$query = "SELECT *
FROM Conference
WHERE Username = :un";
$stmt = $link->prepare($query);
$stmt->bindParam(':un', $usr);
$stmt->execute();
$row = $stmt->fetchAll();
$hash = $row[0]["Password"];
$is_correct = Bcrypt::check($old_pwd, $hash);
if($is_correct) {
$query = "UPDATE Conference
SET `Password`=:new_pwd
WHERE Username = :usr";
$stmt = $link->prepare($query);
$stmt->bindParam(':new_pwd', $new_pwd);
$stmt->bindParam(':usr', $usr);
$stmt->execute();
return true;
} else return false;
} catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
但由于某些原因,当我点击提交按钮后,页面仍为change_password.php
。我不知道为什么,我看过这么多的教程,我的代码与他们的代码相匹配,但由于某种原因,我的代码不会保持在同一页面上。我哪里做错了?
您应该检查js控制台以查看是否有任何错误。无论如何,你的代码已经有错误了。您在函数内部传递变量,而不将它们作为参数同时存在于成功和错误事件中。 – itachi
@Richard尝试在Firefox上进行调试。如果您还没有使用Firebug扩展名。萤火虫控制台上的Net标签显示请求。你可以确定你的问题是在JS还是PHP然后纠正它。 –