[英]Using jQuery's method .ajax() to send a form in PHP
我目前正在開發一個允許用戶更改密碼的表單。 我對jQuery ajax不是很了解。 ajax似乎沒有將數據發送到changepassword.php。 當我不使用ajax時,PHP文件工作正常。 你們能幫我一點嗎?
我根據一些評論更新了我的文件。 當我嘗試提交表單時,它返回“ Doesn't Work
。 所以我猜php是響應,但值沒有到達數據庫。
非常感謝幫助人員。
以下是表單和ajax(更新)
<form id="form_id" method="POST">
<label for="username">Username</label>
<input type="text" name="username" id="username" required />
<label for="old_password">Old Password</label>
<input type="password" name="old_password" id="old_password" required />
<label for="new_password">New Password</label>
<input type="password" name="new_password" id="new_password" required />
<button class="submit">
Submit
</button>
<p class="result"></p>
</form>
<script>
$.ajaxSetup({
cache : false
});
$(".submit").click(function(e) {
$.ajax({
url : "changepassword.php",
type : "POST",
data : $("#form_id").serialize(),
success : function(data) {
if(data == 1) {
$(".result").html("Works");
} else {
$(".result").html("Doesn't Work");
}
}
});
return false;
});
</script>
這是changepassword.php
(更新)
<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);
include_once "../classes/Connect.php";
$connection = new Connect();
$username = $_POST['username'];
$old_password = $_POST['old_password'];
$new_password = $_POST['new_password'];
$result = $connection -> change_password($username, $old_password, $new_password);
if ($result) {
echo 1;
}
?>
這是來自connect.php
類文件的方法change_password()
function change_password($username, $old_password, $new_password){
$query = "UPDATE Account SET password = ? WHERE username = ? AND password = ?";
if ($stmt = $this -> conn -> prepare($query)){
$stmt -> bind_param('sss', md5($new_password), $username, md5($old_password));
if ($stmt -> execute()){
return true;
}
}
}
您對服務器的請求是否成功? 因為我不確定,但如果整個請求失敗,那么你沒有成功,jquery ajax(可能)會尋找錯誤函數,但你沒有提供它 - 所以沒有任何事情發生'。
關於設置ajax數據屬性可能你可以做data: $('#form_id').serialize()
和thid = s將為請求創建正確的字符串 - var1 = value1&var2 = value2但代碼更少。
如果在session_start();
之后你的php文件有問題session_start();
插入以下代碼將提示您出現的問題:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);
祝您好運。 Ivelin
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.