使用jQuery和Ajax通过POST提交表单

时间:2013-08-10 19:12:55

标签: php html ajax jquery

我正在尝试使用jQuery& amp从表单中发布数据阿贾克斯。但是,当我检查我的PHP以查看表单是否已“提交”时,它显示它没有,因为MySQL代码没有运行。我猜我的HTML设置不正确,因此Ajax请求不会将数据发送到我的post-update.php脚本。这是我的代码:

<script type="text/javascript">
    $(document).ready(function() {
        $('#ajax-remove-completion-date').click(function() {
            $.ajax({
                type:'POST',
                url:'post-update.php',
                data: dataString,
                success: function(response) {
                 $('#success-remove-completion-date').removeClass('hidden');
                }
            });
        });
    });

HTML:

<form action="">
    <div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
            <h3 id="myModalLabel3">Remove Completion Date</h3>
        </div>
        <div class="modal-body">
            <p>Are you sure you want to remove the students Completion Date?</p>
        </div>
        <div class="modal-footer">
          <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
          <button class="btn blue" data-dismiss="modal" id="ajax-remove-completion-date">Yes</button>
          <input type="hidden" name="submitted" value="remove-completion-date" />
        </div>
    </div>
</form>

PHP:

<?
session_id();
session_start();

require_once('assets/includes/mysql-connect.php');

/*Check to see if the completion date is being removed*/
if ($_POST['submitted'] == 'remove-completion-date') {
    $query = "UPDATE students SET completion_date = NULL, completed = NULL WHERE student_id = {$_SESSION['student_id']} LIMIT 1";
    $result = mysqli_query($dbc, $query);
} 
?>

1 个答案:

答案 0 :(得分:5)

dataString来自哪里?

最好定义要作为对象发送的数据。它更具可读性,并自动转换为查询字符串。

$(document).ready(function() {
    $('#ajax-remove-completion-date').click(function() {
        $.ajax({
            type:'POST',
            url:'post-update.php',
            data: {
                submitted: 'remove-completion-date'
            },
            success: function(response) {
                $('#success-remove-completion-date').removeClass('hidden');
            }
        });
    });
});

如果您想从字段中获取值,请将submitted设置为:

$('input[name="submitted"]').val()