2012-02-29 04:18
浏览 107

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

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:


<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()" />

The jQuery:

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

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

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

Now, the 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);

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!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

6条回答 默认 最新

  • duanaiguang1960 2012-02-29 04:27
    var myCheckboxes = new Array();
    $("input:checked").each(function() {

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

    解决 无用
    打赏 举报

相关推荐 更多相似问题