为什么我无法使用发布请求使用jquery更新数据库中的数据?

时间:2019-02-17 23:48:49

标签: php jquery mysql

我正在尝试使用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"
));

}

2 个答案:

答案 0 :(得分:1)

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

在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_user"的ID。当然,这是假设PDO(看起来是这样)可以让您做到这一点的,因为键与查询中的占位符未正确匹配,因此不会。

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

就像注释中提到的@Taplar一样,在您的JS中,您还需要阻止“提交”按钮的默认行为。假设我们为e.preventDefault()变量或e设置了一个参数,我们可以使用event来做到这一点(但我懒于键入它)。

希望它对您有用...

答案 1 :(得分:0)

Just as @Taplar said in comment, your click event for the submit button is not being cancelled. So most likely the form will submit before the ajax finishes running, I suggest you to use the equivalent form to send the request asynchronously by setting async: false

$.ajax({
  type: "POST",
  async: false,
  url: publishNotifRequest.php,
  notification: notification,
  id_user: id_user
});