php - 为什么我无法使用发布请求使用 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"
));
}
解决方案
好的,基于其他评论和我自己的观察:
在 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
(但我懒得输入它)。
希望它对你有帮助...
推荐阅读
- javascript - 如何获取单选按钮的值并将其传递给 laravel 中的控制器?
- python - Python字典更新惊喜
- data-structures - Lucene 索引建模 - 为什么使用跳过列表而不是 btree?
- java - Java中是否可以有一个数组或几何图元列表?
- autoencoder - 为什么 VAE 的 z 变量的分布不在 -1 和 1 之间?
- docker - 在 192.168.65.5:53 上查找:没有这样的主机
- oracle - 在 oracle 报告中执行获取结果错误
- spring-boot - Gradle 找不到插件,使用 Spring 初始化程序初始化的 Spring Boot 项目
- javascript - 导出已在导出函数中使用的变量
- asp.net-web-api - 哪种 Insights 实施可以保证记录所有异常?