我試圖在我的網站中實現密碼更改功能。我已經完成了所有密碼更改腳本,驗證等。但現在我需要阻止頁面進入腳本頁面或刷新。當用戶點擊提交按鈕時,除了顯示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然後糾正它。 –