skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You should use Array.prototype.join() instead of JSON.stringify

    checked =  checked_arr.join(',');
    

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search