0

I want to get all the values of the checkboxes that are checked, in a string that I can pass through ajax.

<input value="1" class="customer" type="checkbox">
<input value="2" class="customer" type="checkbox">
<input value="3" class="customer" type="checkbox">
<input value="4" class="customer" type="checkbox">
<input value="5" class="customer" type="checkbox">

so if 2 and 5 are checked, I want to create a variable var checked='2,5'

var checked_arr = [];
$('.customer:checked').each(function(){
    checked_arr.push($(this).val());
});
checked = JSON.stringify(checked_arr);
$.ajax({
    type    : 'POST',
    url     : '//'+base_url+'/ajax/customers.php',
    data    : 'checked='+checked,
    success : function(data) {
    }
}); 

I think I need to json encode it to pass the array through, but I dont even seem to be creating the array properly. I think I am missing something on pushing the values into the array.

Source
  • 1,026
  • 4
  • 11
  • 23

2 Answers2

2

JSON.stringify() will create ["2","5"], not 2,5. You should use

var checked = checked_arr.join(',');

Or you could just pass the array itself:

data: {checked: checked_arr},

$.ajax will format this so that $_POST['checked'] will be an array.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You should use Array.prototype.join() instead of JSON.stringify

checked =  checked_arr.join(',');

For more details, you can read Wayne's answer here

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56