簡體   English   中英

在沒有頁面刷新的情況下在表單上提交復選框值 AJAX PHP

[英]Submit checkbox value on form without page refresh 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 的頁面上

如果它是輸入文本但不適用於復選框,則此特定代碼有效。 請幫助我,這樣我才能好好學習。 提前致謝。

.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 序列化

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM