首页 > 解决方案 > 为什么我无法使用发布请求使用 jquery 更新数据库中的数据?

问题描述

我正在尝试使用 Jquery 将一些数据更新到我的数据库中,但没有任何反应。

<form action="" method="POST" class="container form-control text-center">

ID : <input type="text" name="id_user" id="id_user" value="<?= $userInfo['id_user']; ?>" class="form-control" disabled></input><br>
<input type="text" id="notification" name="notification" class="form-control" placeholder="Écrivez une notification..."></input><br>


<input type="submit" class="publishNotif" value="publish">

<script type="text/javascript">


$('.publishNotif').click(function(){

    var notification = $("#notification").val();

    $.post("publishNotifRequest.php", {
        notification: notification,
        id_user: id_user
    });

});

在名为“publishNotifRequest.php”的文件中:

if(isset($_POST['notification']) AND !empty($_POST['notification']) AND isset($_POST['id_user']) AND !empty($_POST['id_user'])){

$insertNotif = $bdd->prepare('UPDATE USERS SET notification = :notification WHERE id_user = :id_user');

$insertNotif->execute(array(
    "notification" => trim(htmlspecialchars($_POST['notification'])), // trim supprime les espaces debut et fin de chaine
    "id_user"
));

}

标签: phpjquerymysql

解决方案


好的,基于其他评论和我自己的观察:

在 JS 中

$('.publishNotif').click(function(e){
    e.preventDefault();    // --- add this
    var notification = $("#notification").val();

    $.post("publishNotifRequest.php", {
        notification: notification,
        id_user: id_user
    });
});

在 PHP 中

if(isset($_POST['notification']) AND !empty($_POST['notification']) AND isset($_POST['id_user']) AND !empty($_POST['id_user'])){

    $insertNotif = $bdd->prepare('UPDATE USERS SET notification = :notification WHERE id_user = :id_user');

    $insertNotif->execute(array(
        "notification" => trim(htmlspecialchars($_POST['notification'])), 
        "id_user"      => $_POST['id_user']  // --- add this
    ));

}

另请注意评论,其中显示了我所做的更改。我看到的最大问题是:

$insertNotif->execute(array(
    "notification" => trim(htmlspecialchars($_POST['notification'])), // trim supprime les espaces debut et fin de chaine
    "id_user"  //<<----- no value for this "key"
));

因为你刚刚"id_user"在那里,PHP 将使它成为一个字符串文字(数组中的元素),而不是你的数组的键。然后因为这是您需要更新数据库的 ID,它找不到要更新的行,因为那里没有 ID "id_user"。这当然是假设 PDO(它看起来像)会让你这样做,因为键与查询中的占位符不正确匹配,所以它不会这样做。

如果您查看请求的返回或错误日志,您可能会看到类似PDOException - wrong number of parameters supplied.PDOStatement::execute()

同样正如评论中提到的@Taplar,在您的 JS 中,您需要防止提交按钮的默认行为。我们可以e.preventDefault()假设我们为e变量 or设置了一个参数event(但我懒得输入它)。

希望它对你有帮助...


推荐阅读