Somename Somename - 4 months ago 11
jQuery Question

How to pass array with all elements with jquery to php

I am trying to pass an array from jQuery to PHP.

<input type="checkbox" id="name1" name="name[]" value="name1"> Name1
<input type="checkbox" id="name2" name="name[]" value="name2"> Name2
<input type="checkbox" id="name3" name="name[]" value="name3"> Name3<br />

<input type="checkbox" id="phone1" name="phone[]" value="samsung"> Samsung
<input type="checkbox" id="phone2" name="phone[]" value="nokia"> Nokia
<input type="checkbox" id="phone3" name="phone[]" value="motorola"> Motorola<br />


$(document).ready(function() {
$(":checkbox").on('change', function() {
var group = [];
var mygroup = {};

$(':checkbox:checked').each(function(i){
var val = this.value;
var name = this.name;
mygroup[name] = val;
var all = name + "=" + val;
group.push(all);

$.ajax({
type: "POST",
url: 'testdraft1.php',
data: mygroup, // TRIED WITH group and all also. Doesn't work.
success: function(data) {
$("#result").html(data);
}
});
});
});
});


With this code the array is passed to PHP but with only 1 element. Even if I select multiple elements. What am I doing wrong?

Answer

This works and is perhaps simpler than using FormData. (Note that I've changed name[] to name and phone[] to phone.) I've also moved the AJAX call outside of the each loop.

HTML:

<input type="checkbox" id="name1" name="name" value="name1"> Name1
<input type="checkbox" id="name2" name="name" value="name2"> Name2
<input type="checkbox" id="name3" name="name" value="name3"> Name3<br />

<input type="checkbox" id="phone1" name="phone" value="samsung"> Samsung
<input type="checkbox" id="phone2" name="phone" value="nokia"> Nokia
<input type="checkbox" id="phone3" name="phone" value="motorola"> Motorola<br />

JavaScript:

$(document).ready(function() {
    $(":checkbox").on('change', function() {
        var mygroup = {};

        $(':checkbox:checked').each(function(i) {
            var val = this.value;
            var name = this.name;

            mygroup[name] = (mygroup[name] || []).concat([val]);
        });

        $.ajax({ 
            type: "POST", 
            url: 'testdraft1.php',
            data: mygroup,
            success: function(data) {
                $("#result").html(data);
            }
        });
    });
});