简体   繁体   中英

Sending multiple groups of checkboxes to PHP via AJAX

I have checked various SO questions

  1. How to send a checkbox group via ajax in jquery?
  2. serializing checkboxes in jQuery

But none of these send more than one set of checkboxes.

I have a form with a series of checkboxes:

<input type="checkbox" name="color[]" value="1"/>
<input type="checkbox" name="color[]" value="2"/>
...
<input type="checkbox" name="size[]" value="1"/>
<input type="checkbox" name="size[]" value="2"/>
...

There are also some other non checkboxes on the form.

I send this to php via ajax:

$.ajax({
    url: '/filter',
    type: 'POST',
    data: { filter: $(self.form).serializeArray()},
    dataType: 'JSON'
});

I then need to get each set of checkbox values in PHP. So I output the post:

array (size=4)
  0 => 

array (size=2)
  'name' => string 'color[]' (length=7)
  'value' => string '4' (length=1)
1 => 
array (size=2)
  'name' => string 'color[]' (length=7)
  'value' => string '6' (length=1)
2 => 
array (size=2)
  'name' => string 'length[]' (length=8)
  'value' => string '3' (length=1)
3 => 
array (size=2)
  'name' => string 'length[]' (length=8)
  'value' => string '5' (length=1)

But how can I get each set of values? I want a var with all colors, and a var with all sizes.

Just to clarify - I'm looking for a way in PHP to get the colors into an array and another array for lenths.

Something like:

$_POST['filter']['color'];

Do you want the result already been a array of checked value when send to php? If it is, then you need to pre-process it:

var result = [];
$('input[type="checkbox"][name="color[]"]').each(function(_, ele) {
    if ($(ele).prop('checked')) {
       result.push($(ele).attr('value'));
      }
});

Hope its what you want.

Here's a bit of PHP code that will convert your $_POST to a new array called $filter

$filter = array();
foreach ($_POST as $checkbox) {
    if (substr($checkbox['name'],-2) == '[]') {
        $name = substr($checkbox['name'],0,-2);
        if (!array_key_exists($name,$filter)){
            $filter[$name] = array();
        }
        array_push($filter[$name],$checkbox['value']);
    }
}
print_r($filter);

What it does is:

  1. It checks if name ends with [] if that's the case it is assumed to be a checkbox, if not it's ignored.
  2. It will generate a new array in $filter that contains an array for each checkbox group

So $filter to your example $_POST will look like this:

Array ( 
  ['color'] => Array ( 
    [0] => 4 
    [1] => 6 
  ) 
  ['length'] => Array ( 
    [0] => 3 
    [1] => 5 
  ) 
)
<?php
$colors = $_POST['filter']['color'];

print_r($colors);
?>

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