0

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 supplied for foreach()" because I don't think it's getting any other value except the first. Where am I going wrong?

1 Answer 1

5

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Would I need to change my jQuery call? The only way I'm sending the form is by jQuery.post()
no, you won't need to change the jQuery code; serialize() will just work with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.