Problem serializing checkboxes with jQuery and PHP
I have checkboxes (all with the same 'name' attribute) that I want sent to a PHP controller. Here's a brief snippet of my markup:
<script type="text/javascript">
$(document).ready(function(){
$(".someButton").click(function(){
$.post("my_controller.php",$("#userForm").serialize());
});
});
</script>
<?php
echo '<form id="userForm">';
foreach($users as $user)
{
echo '<input name="user_id" value="'.$user->id.'">';
}
echo '</form>';
?>
I then want my controller to send these values as a unified array to a model where it can then do a foreach statement. The controller logic should (I think) be something like this:
foreach($_POST['user_id'] as $user_id)
{
$user_array[] = $user_id;
}
$this->model->method($user_array);
But I keep getting errors like "Invalid argument su开发者_Go百科pplied for foreach()" because I don't think it's getting any other value except the first. Where am I going wrong?
If you have multiple checkboxes with the same name and want to send them as an array of checked checkboxes, add a []
suffix to the checkbox names:
<input type="checkbox" name="user_id[]" value=... />
Then in your PHP you can do this:
$user_array = isset($_POST['user_id']) ? $_POST['user_id'] : array();
精彩评论