简体   繁体   中英

How to send an checkbox data as an array to a php script via jquery/ajax

I have few checkbox like this,

<input type='checkbox' name='name[]' value='1' />
<input type='checkbox' name='name[]' value='2' />
<input type='checkbox' name='name[]' value='3' />
<input type='checkbox' name='name[]' value='4' />
<input type='checkbox' name='name[]' value='5' />

And my php processing code is below,

<?php
$check=$_POST['name'];

foreach($check as $arr){
//code for saving data in database
}

My problem is, I am trying to send the check box data via jquery/ajax. But I could not send those data to the php page as an array.

Please tell me I could I do that.

You can just serialize() or serializeArray() the checkboxes and send them to PHP :

$.ajax({
    url  : 'processing.php',
    data : $('[name="name[]"]').serialize()
}).done(function(result) {
    // ta da
});

Note that only checked boxes will be serialized, as there is generally no need to do anything for unchecked boxes.

View

        <input type='checkbox' name='name[]' class="checkBoxGroup" value='1' />
        <input type='checkbox' name='name[]' class="checkBoxGroup" value='2' />
        <input type='checkbox' name='name[]' class="checkBoxGroup" value='3' />
        <input type='checkbox' name='name[]' class="checkBoxGroup" value='4' />
        <input type='checkbox' name='name[]' class="checkBoxGroup" value='5' />

Script

        $ary=$(".checkBoxGroup").serializeArray();
        alert($ary[0]['value']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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