0

I am trying to pass a form of checkboxes through ajax. All I really want is a list of all the values of the checked check boxes.

<form id="filters_form">
<input type="checkbox" name="speed" value="1">
<input type="checkbox" name="speed" value="4">
<input type="checkbox" name="accuracy" value="2">
<input type="checkbox" name="measurement-types" value="3">
</form>

This is how I am seriaziling the data

form_val = $('#filters_form').serialize();
$.ajax({        
    type    : 'POST',
    url     : '//localhost/ajax/filters.php',
    data    : form_val,
    success : function(data) {}
});

The issue seems to be we when more than one checkbox with the same name is checked. When the data is sent through ajax we have speed+=1&speed+=4&accuracy+=2 But if I print_r($_POST) then I only get

Array
(
    [speed] => 4
    [accuracy] => 2
)

It only takes one instance of each name. How can I get the full data?

Source
  • 1,026
  • 4
  • 11
  • 23

1 Answers1

2

Why would you use the same name for different checkbox to hold different values? Why can you not use unique names for your each checkbox?

Though you can share the same name for a group of your radio buttons because only one radio button can be selected in that group and only that selected radio button's value is sent to the server file.

But in case of checkbox, you can not use the same name twice or more. Because, in server file say PHP, only the last value checked will be considered. The previous value will no longer exist there. This confirms to the concept of a variable which tells us an ordinary variable can hold only a single value at a time. If a new value is stored in it, the previous value is washed out.

If you still want to use the same name for your different checkboxes, then using array will be an ideal solution. You can do it this way:

<form id="filters_form">
    <input type="checkbox" name="speed[]" value="1">
    <input type="checkbox" name="speed[]" value="4">
    <input type="checkbox" name="accuracy" value="2">
    <input type="checkbox" name="measurement-types" value="3">
</form>

On server side, you will collect data as:

Array
(
    [speed] => Array
        (
            [0] => 1
            [1] => 4
        )

    [accuracy] => 2
    [measurement-types] => 3
)

Thereafter, you can use this data via some looping code.

I think an excellent post that can guide you is How to pass an array within a query string?

Community
  • 1
  • 1
Sachin
  • 1,646
  • 3
  • 22
  • 59