I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Return checkboxes array to php via jquery?

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']);
?>

Upvotes: 1

Views: 299

Answers (2)

Rafay
Rafay

Reputation: 31033

you need to escape the []

var options = $("input:checkbox[name='option\\[\\]']");

Upvotes: 1

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)
    });
});

Upvotes: 0

Related Questions