首页 > 解决方案 > 在表单上提交复选框值而不刷新页面 AJAX PHP

问题描述

我刚开始学习 ajax,我同意它真的很棒而且节省时间。

但是我在这一点上卡住了发送表单数据而没有重新加载页面。

下面是我的html代码。

<form id="form4" method="post">
  <input type="checkbox" name="test" id="agreed" value="check">
  <br>
  <br>
  <input type="submit" id="form-submit" name="submit" value="Send">
  <p class="form-message"></p>
</form>

下面是我的 Ajax 脚本

<script>
    $(document).ready(function() {
        $("#form4").submit(function(event) {
            event.preventDefault();
            var action = 'another_test';
            var agreed = $("#agreed").val();
            var submit = $("#form-submit").val();
            $(".form-message").load("test3.php", {
                test: agreed,
                submit: submit,
                action: action
            });
        });
    });
</script>

下面是我的php代码

<?php

  if (isset($_POST['action'])) {

        if ($_POST['action'] == 'another_test') {

            $test = $_POST["test"];
            $errorEmpty = false;


            if (!empty($test)) {
                echo "<p>Click the checkbox pls</p>";
                $errorEmpty = true;
            }

            else {
                echo "<p>Checkbox clicked</p>";
            }
        } else {
            echo "Error.. cant submit";
        }
    }

?>
<script>

    var errorEmpty = "<?php echo $errorEmpty ?>";
</script>

php 文件位于另一个名为 test3.php 的页面上

如果它是输入文本,则此特定代码有效,但不适用于复选框。请帮助我,这样我才能学得好。提前致谢。

标签: javascriptphpjqueryajax

解决方案


.load()(根据文档)执行 GET 请求,而不是 POST,但您的 PHP(如$_POST参考文献所示)期待 POST 请求 - 通常使用 POST 提交表单数据是有意义的。

所以你最好使用$.post()- 这将发送一个 POST 请求。然后您可以处理响应并将其加载到由该请求触发的“完成”回调中的“表单消息”元素中。

注意您还可以通过将“action”变量作为隐藏字段放入表单中来缩短代码,然后在一个命令中简单地序列化表单,而不是单独提取每个值。

例子:

HTML:

<form id="form4" method="post">
  <input type="checkbox" name="test" id="agreed" value="check">
  <br>
  <br>
  <input type="submit" id="form-submit" name="submit" value="Send">
  <input type="hidden" action="another_test"/>
  <p class="form-message"></p>
</form>

JavaScript

$(document).ready(function() {
    $("#form4").submit(function(event) {
        event.preventDefault();

        $.post(
          "test3.php", 
          $(this).serialize()
        ).done(function(data) { 
            $(".form-message").html(data);
        });
    });
});

文档:

jQuery 加载

jQuery 帖子

jQuery 序列化


推荐阅读