Send multiple checkbox data to PHP via jQuery ajax()

111,648

Solution 1

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

Solution 2

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

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

 echo var_export($_POST);

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

Solution 3

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']);

Solution 4

You may also try this,

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

console.log(arr);

Solution 5

    $.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);
Share:
111,648

Related videos on Youtube

John Anderson
Author by

John Anderson

Updated on March 21, 2020

Comments

  • John Anderson
    John Anderson about 4 years

    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:

    The 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:

    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

    $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!

  • John Anderson
    John Anderson about 12 years
    Thanks. I changed that but I'm still not receiving the data on the PHP end. I've tried several different methods for handling the checkboxes with jQuery (I found most of the ideas on this site), but none of them have worked. My code creates a mySQL database record, but the checkboxes field is always empty, even though I am checking up to 8 different checkboxes in the form that is sent.
  • Lucas
    Lucas almost 12 years
    thanks @WinnMinnSoe for making me discover the .serialize method! =)
  • KalC
    KalC almost 11 years
    Thanks @WinnMinnSoe. Very, very neat!!
  • Andy
    Andy over 7 years
    Uncaught ReferenceError: data is not defined
  • Damian
    Damian almost 7 years
    @Andy myCheckboxes.push($(this).val());
  • hakkikonu
    hakkikonu almost 6 years
    myCheckboxes = data['myCheckboxes[]'].push($(this).val()); is final step