通过 jQuery ajax() 向 PHP 发送多个复选框数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9493531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:56:57  来源:igfitidea点击:

Send multiple checkbox data to PHP via jQuery ajax()

phpjqueryajaxcheckbox

提问by John Anderson

I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:

我想通过 jQuery 的 .ajax() 在我的网站上提交一个包含 textarea 字段和输入字段(type="checkbox" 带有任意/可变数量的复选框)的 POST 表单。PHP接收textarea数据,ajax响应正确显示给用户。但是,PHP 似乎没有收到复选框数据(是否已选中)。我怎样才能让它工作?这是我的代码:

The HTML:

HTML:

<form method="post" action="myurl.php" id=myForm>
    <textarea id="myField" type="text" name="myField"></textarea>
    <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
    <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
    ...(maybe some more checkboxes - dynamically generated as necessary)
    <input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>

The jQuery:

jQuery:

function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {

        var myCheckboxes = new Array();
        $("input:checked").each(function() {
           myCheckboxes.push($(this).val());
        });

        $.ajax({
            type: "POST",
            url: "myurl.php",
            dataType: 'html',
            data: { myField:$("textarea[name=myField]").val(),
                    myCheckboxes:myCheckboxes },
            success: function(data){
                $('#myResponse').html(data)
            }
        });
        return false;
});
});

Now, the PHP

现在,PHP

$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
    for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
    {
        // do some stuff, save to database, etc.
    }
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);

Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!

一切正常:提交表单时,新记录存储在我的数据库中,响应被ajaxed回网页,但未发送复选框数据。我想知道哪些复选框已被选中(如果有)。我读过 .serialize()、JSON 等,但没有一个有效。我是否必须在 jQuery 和 PHP 中序列化/JSON?如何?使用复选框发送表单数据时,一种方法是否比另一种方法更好?我已经被困在这个问题上 2 天了。任何帮助将不胜感激。提前致谢!

采纳答案by sbczk

var myCheckboxes = new Array();
$("input:checked").each(function() {
   data['myCheckboxes[]'].push($(this).val());
});

You are pushing checkboxes to wrong array data['myCheckboxes[]']instead of myCheckboxes.push

您将复选框推送到错误的数组data['myCheckboxes[]']而不是myCheckboxes.push

回答by Winn Minn Soe

Yes it's pretty work with jquery.serialize()

是的,它非常适合 jquery.serialize()

HTML

HTML

<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
 <div id="myResponse"></div>

JQuery

查询

function submitForm() {
var form = document.myform;

var dataString = $(form).serialize();


$.ajax({
    type:'POST',
    url:'myurl.php',
    data: dataString,
    success: function(data){
        $('#myResponse').html(data);


    }
});
return false;
}

NOW THE PHP, i export the POST data

现在 PHP,我导出 POST 数据

 echo var_export($_POST);

You can see the all the checkbox value are sent.I hope it may help you

您可以看到发送的所有复选框值。希望它可以帮助您

回答by Kamal Joshi

Check this out.

看一下这个。

<script type="text/javascript">
    function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {

        var myCheckboxes = new Array();
        $("input:checked").each(function() {
           myCheckboxes.push($(this).val());
        });

        $.ajax({
            type: "POST",
            url: "myurl.php",
            dataType: 'html',
            data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
            success: function(data){
                $('#myResponse').html(data)
            }
        });
        return false;
});
});
}
</script>

And on myurl.php you can use print_r($_POST['myCheckboxes']);

在 myurl.php 上你可以使用 print_r($_POST['myCheckboxes']);

回答by user3391228

    $.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like.

所以我只会遍历选中的框并构建数组。就像是。

       var data = { 'user_ids[]' : []};
        $(":checked").each(function() {
       data['user_ids[]'].push($(this).val());
       });
        $.post("ajax.php", data);

回答by SagarPPanchal

You may also try this,

你也可以试试这个

var arr = $('input[name="myCheckboxes[]"]').map(function(){
  return $(this).val();
}).get();

console.log(arr);

回答by blackpla9ue

The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.

您目前拥有的代码似乎没问题。使用此检查复选框数组包含的内容。将此代码添加到您的 php 脚本顶部,并查看复选框是否正在传递给您的脚本。

echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;