简体   繁体   English

如何在刷新时重新填充表单中的复选框并将表单值发布到页面?

[英]How to repopulate checkboxes in form on refresh AND post the form values to page?

I am using an ajax script to repopulate checkboxes on a page when the page refreshes or is sent to another page and then back again. 当页面刷新或发送到另一个页面然后再次返回时,我正在使用ajax脚本重新填充页面上的复选框。 The script works fine as the checkboxes will still be checked after page refresh. 该脚本可以正常工作,因为刷新页面后仍会选中该复选框。

The problem I have is these checkboxes work as filters. 我的问题是这些复选框可以用作过滤器。 So when clicked it POSTS to the page and my php script puts each value into a string for my query. 因此,当单击它时,将其发布到页面,并且我的php脚本将每个值放入一个字符串以供查询。 When a page is refreshed the checkboxes stay checked but are not posting the values to the page. 刷新页面时,复选框会保持选中状态,但不会将值发布到页面上。 How can I make this Ajax script POST the values of the form after it repopulates my checked checkboxes on page refresh? 重新填充页面刷新时选中的复选框后,如何使此Ajax脚本发布表单的值?

Here is Ajax script: 这是Ajax脚本:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>

<script>
  function handleButtonClick(button){
    if ($(button).text().match("Check all")){
      $(":checkbox").prop("checked", true)
    } else {
      $(":checkbox").prop("checked", false)
    };
    updateButtonStatus();
  }

  function updateButtonStatus(){
    var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
    $("button").text(allChecked? "Uncheck all" : "Check all");
  }

  function updateCookie(){
    var elementValues = {};
    $(":checkbox").each(function(){
      elementValues[this.id] = this.checked;
    });

    elementValues["buttonText"] = $("button").text();
    $.cookie('elementValues', elementValues, { expires: 7, path: '/' })
  }

  function repopulateFormELements(){
    var elementValues = $.cookie('elementValues');
    if(elementValues){
      Object.keys(elementValues).forEach(function(element) {
        var checked = elementValues[element];
        $("#" + element).prop('checked', checked);
      });

      $("button").text(elementValues["buttonText"])
    }
  }

  $(":checkbox").on("change", function(){
    updateButtonStatus();
    updateCookie();
  });

  $("button").on("click", function() {
    handleButtonClick(this);
    updateCookie();
  });

  $.cookie.json = true;
  repopulateFormELements();


</script>

And the PHP on same page that puts what is checked into a string for my query 以及同一页面上的PHP,它将检查的内容放入字符串以供查询

if (isset($_POST["2kandunder"])) {
$arguments[] = "AND `2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "AND `2kto4k` = 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "AND 4kandup = 'yes'";
}

if(!empty($arguments)) {
$str = implode($arguments);
}

And html form 和html表格

 <form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" id="1" onchange="$('#form').submit();" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> $2000 And Under   

<input type="checkbox" name="2kto4k" class="checkbox" id="2" onchange="$('#form').submit();" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> $2001 To $4000

<input type="checkbox" name="4kandup"  class="checkbox" id="3" onchange="$('#form').submit();" <?=(isset($_POST['4kandup'])?' checked':'')?>/> $4001 And Up   

I have tried adding the following to my ajax but I am totally new to ajax and it was a total guess. 我曾尝试将以下内容添加到我的ajax中,但是我对ajax完全陌生,这完全是猜测。 This code makes the page start blinking and the page will go to "page not found" after about 5 seconds. 此代码使页面开始闪烁,并且大约5秒钟后页面将转到“找不到页面”。

$('#form').submit(); 

As you store the cookie, you can use it information in PHP as well to repopulate the query filter and the checkboxes on the form 存储cookie时,您也可以在PHP中使用它的信息来重新填充查询过滤器和表单上的复选框。

<?php

    $checkboxes = array('checkbox1' => false, 'checkbox2' => false, 'checkbox3' => false, 'checkbox4' => false, );

    if (isset($_COOKIE['elementValues'])) {
        /* 
            Cookie values are stored like JSON
        */
        $raw = json_decode($_COOKIE['elementValues'], true); //cast to array
        var_dump($raw);
        foreach($raw as $input_name => $value) {
            if (isset($checkboxes[$input_name])) {
                $checkboxes[$input_name] = $value; //true/false
            }
        }
    }

    var_dump($checkboxes);


    if (isset($_POST["checkbox1"]) || $checkboxes['checkbox1']) {
        $arguments[] = "AND `2kandunder` = 'yes'";
    }
    if (isset($_POST["checkbox2"]) || $checkboxes['checkbox2']) {
        $arguments[] = "AND `2kto4k` = 'yes'";
    }
    if (isset($_POST["checkbox3"]) || $checkboxes['checkbox3']) {
        $arguments[] = "AND 4kandup = 'yes'";
    }

    $str = '';
    if(!empty($arguments)) {
        $str = implode(' ',$arguments);
    }

    echo 'QUERY FILTER : ' . $str;
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Checkbox state - Coookies</title>
    </head>
    <body>
        <form action="#" method="POST">
            <?php
                foreach($checkboxes as $input_name => $checked) {
                    echo '<input type="checkbox" id="'.$input_name.'" name="'.$input_name.'"'.($checked?' checked':'').' />';
                }
            ?>
            <input type="submit" />
        </form>


        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>        
        <script>
          function handleButtonClick(button){
            if ($(button).text().match("Check all")){
              $(":checkbox").prop("checked", true)
            } else {
              $(":checkbox").prop("checked", false)
            };
            updateButtonStatus();
          }

          function updateButtonStatus(){
            var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
            $("button").text(allChecked? "Uncheck all" : "Check all");
          }

          function updateCookie(){
            var elementValues = {};
            $(":checkbox").each(function(){
              elementValues[this.id] = this.checked;
            });

            elementValues["buttonText"] = $("button").text();
            $.cookie('elementValues', elementValues, { expires: 7, path: '/' })
          }

          $(":checkbox").on("change", function(){
            updateButtonStatus();
            updateCookie();
          });

          $("button").on("click", function() {
            handleButtonClick(this);
            updateCookie();
          });

          $.cookie.json = true;
        </script>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM