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

thr*_*ee3 0 html php ajax jquery

我正在尝试使用jQuery和Ajax从表单中发布数据.但是,当我检查我的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');
                }
            });
        });
    });
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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);
} 
?>
Run Code Online (Sandbox Code Playgroud)

ep0*_*ep0 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');
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

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

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