通过AJAX更新数据库中的变量

时间:2017-03-13 20:06:28

标签: php jquery mysql ajax

所以,我一直在用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文件中出错了,但我不知道在哪里。请让我知道我做错了什么,因为我没有得到在时间日期保存 - 并且它没有保存在数据库中。提前谢谢!

1 个答案:

答案 0 :(得分:0)

您的PHP代码似乎期待一个代表表单的POST变量,但这不是jQuery serialize产生的。它生成一个POST字符串,其中包含所有(成功)控件及其值的名称,因此PHP将为每个控件接收一个POST参数。

编辑:澄清一下,我的意思是,如果formulier24是表单的名称,则isset $_POST['formulier24']的{​​{1}}检查将始终返回false。