Im trying to send an array of checkboxes (value) to PHP via jquery. How can that be done?

See the following example:

<input type="checkbox" name="option[]" value="0"> Small
<input type="checkbox" name="option[]" value="1"> Medium
<input type="checkbox" name="option[]" value="2"> Large
<input type="checkbox" name="option[]" value="3"> X-Large

<input id="ButtonAdd" type="button" value="Add" />

jQuery code, couldn't get to work:

$("#ButtonAdd").click(function() { 
    var options = $("input:checkbox[name='option[]']");
     $.post("ajax_extras.php", { options:options  },
       function(data)  {
         console.log(data)
    });
});

ajax_extras.php file:

<?php
 print_r($_POST['options']);
?>
link|improve this question

you may need to escape the brackets inside the brackets: var options = $("input:checkbox[name='option\\[\\]']"); – Blazemonger Sep 13 '11 at 19:23
@mblase75 i think single slash will escape it ? – 3nigma Sep 13 '11 at 19:25
nope you are right `\\` are needed – 3nigma Sep 13 '11 at 19:27
feedback

2 Answers

up vote 1 down vote accepted

you need to escape the []

var options = $("input:checkbox[name='option\\[\\]']");
link|improve this answer
Thanks, that work but my browser freeze when it attempting to do ajax or something... I have tried to remove ajax code and it work.. any clue? – user791022 Sep 13 '11 at 19:30
by freeze you mean freeze and then unfreeze or just freezes and then craches? may be you are handling a lot of data? – 3nigma Sep 13 '11 at 19:34
The data is only print_r($_POST['options']); and only few tickboxes – user791022 Sep 13 '11 at 20:40
feedback

Add a class attribute to the checkboxes and do instead:


$("#ButtonAdd").click(function() { 
    var options = $("input[type=checkbox].checks");
     $.post("ajax_extras_add_extras.php", { options:options  },
       function(data)  {
         console.log(data)
    });
});
link|improve this answer
I dont think input[type=checkbox].checkk would work because I have couple of tickboxes that is not belong with option[] name. I only want to send data to php that has option[] name – user791022 Sep 13 '11 at 19:22
Then you place the class wherever you see fit, that's up to you. – Joel Alejandro Sep 14 '11 at 0:53
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.