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.
2
Answers
JSON.stringify()
will create["2","5"]
, not2,5
. You should useOr you could just pass the array itself:
$.ajax
will format this so that$_POST['checked']
will be an array.You should use Array.prototype.join() instead of
JSON.stringify
For more details, you can read Wayne’s answer here