views:

3618

answers:

4

Hello

How to pass multiple checkboxes using jQuery ajax post

this is the ajax function

 function submit_form(){
 $.post("ajax.php", {
 selectedcheckboxes:user_ids,
 confirm:"true"
 },
 function(data){
  $("#lightbox").html(data);
  });
 }

and this is my form

<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
+5  A: 

From the jquery docs for POST :

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like

var data = { 'user_ids[]' : []};
$(":checked").each(function() {
  data['user_ids[]'].push($(this).val());
}
$.post("ajax.php", data);
Paul Tarjan
Thanks for the help
ahmed
i am still unable to POST it.. it gives object Object if i do a window.alert for data... where can the problem be??
mkamthan
Should it not be data.user_ids.push($(this).val()); ?
Naeem Sarfraz
well, you want data to be an object with a key "user_ids[]" and a value of an array of strings. (like in the first part of my post). I'll wrap this in $ since val is undefined on a common node.
Paul Tarjan
A: 

If you're not set on rolling your own solution, check out this jQuery plugin:

malsup.com/jquery/form/

It will do that and more for you. It's highly recommended.

Gabriel Hurley
A: 

Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.

var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
 data.push($(this).val());
});
Phil Jackson
A: 

Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.

var data = { 'venue[]' : []};

$("input:checked").each(function() {
   data['venue[]'].push($(this).val());
});

In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)

simnom