【发布时间】:2017-03-13 20:06:28
【问题描述】:
所以,我一直在练习 PDO,请参阅我的 earlier asked question,现在我被困在以下点:
我想在不按下按钮的情况下更新数据库变量,我认为最好通过 AJAX 来实现。
一些代码: General.JS
var timeoutId;
$('form input').on('input propertychange change', function() {
console.log('Invoer bewerking');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
// Runs 1 second (1000 ms) after the last change
saveToDB();
}, 1000);
});
function saveToDB()
{
console.log('Opslaan naar Database');
form = $('.formulier24');
$.ajax({
url: "ajax2.php",
type: "POST",
data: form.serialize(), // serializes the form's elements.
beforeSend: function(xhr) {
// Let them know we are saving
$('.HowAbout').html('Opslaan...');
},
success: function(data) { console.error(data) ;
var jqObj = jQuery(data); // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()
// Now show them we saved and when we did
var d = new Date();
$('.HowAbout').html('Opgeslagen om: ' + d.toLocaleTimeString());
},
});
}
// This is just so we don't go anywhere
// and still save if you submit the form
$('.formulier24').submit(function(e) {
saveToDB();
e.preventDefault();
});
ajax.php 文件:
<?php
include('verbinding.php');
if(isset($_POST['formulier24'])) {
$sql = "UPDATE INTO evenement SET username = :username, hours = :hours";
$parameters = array($_POST["username"], $_POST["hours"]);
try {
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':hours', $_POST['hours']);
$result = $stmt->execute($parameters);
$return = "Updated data successfully!";
} catch (PDOException $e) {
$return = "Could not update data! Error: " . $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($return);
}
?>
连接文件 (verbinding.php) 100% 正常工作。我想我在 ajax.php 文件中犯了一个错误,但我不知道在哪里。请让我知道我做错了什么,因为我没有得到 Saved at time date-提及并且它没有保存在数据库中。提前致谢!
【问题讨论】:
-
有什么问题?你没有说错误
-
是的,错误是什么?对于问题的“改进代码”部分,你应该去不同的堆栈交换站点,我认为是“代码审查”
-
我的错。更新! ^^
-
您有任何 PHP 错误吗?
-
哦,对了,这不存在,您需要添加自己的函数来拉取参数化查询。 EG:stackoverflow.com/questions/210564/… 无论如何,您的查询看起来不错,但很可能您的 POST 变量无效/表单中的名称不正确,请在顶部执行 var_dump($_POST) 以查看发生了什么