[英]Ajax returns success but doesn't change the database
我正在開發一個小js腳本,以Facebook以前的方式編輯配置文件(單擊按鈕,進行編輯並保存,而無需重新加載頁面)。 問題是,當我運行它時,ajax函數返回成功但對數據庫沒有任何更改。 os js函數是這樣的:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"¶meter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(忽略$ t東西,以某種方式這樣工作,但是如果我使用$(this)則不是)
Ajax成功執行代碼,但不更新數據庫上的任何內容。
該數據庫的PHP代碼為:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
編輯:指出,這可能是嘗試將列名作為參數傳遞的問題。 將代碼更改為以下內容,但沒有成功:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
這行:
$stmt->execute(array($parameter, $data. $id));
我認為應該是
$stmt->execute(array($parameter, $data, $id));
(注意$data
之后的逗號)
這可能無法解決您的問題,但是可以為您提供問題的更好指示。
首先,您沒有檢查它是否起作用,因為您的updateProfile
函數什么也不返回。
修改您的updateProfile
函數,使其返回受影響的行數。 (順便說一句,這是編寫函數的一種更安全的方法。如果可以在調用此函數之前檢查或限制$ parameter的值,則它不太容易被SQL注入。)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
在調用此函數的腳本中,獲取值並將其作為響應發送回。 我們將發送回JSON。
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
在您的JavaScript文件中,進行以下更改:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.