I need to send a group of checkboxes (with some other data as well) via ajax in jquery.
What I\'ve done so far is:
var arr = $(\'#somediv input[type
Use serialize()
, as val()
just takes the value of the first element in the jquery collection.
http://api.jquery.com/serialize/
var postdata = $('#somediv input[type="checkbox"]').serialize();
$.post("/somephpfile.php", postdata, function(data) {...
Ran into a similar problem and after much pulling of hair fixed it with SerializeArray
HTML
<input type="checkbox" name="userList[]" value="<?=$userID;?>" /><?= $userName;?>
jQuery
var userList = $('input[type=checkbox]:checked').serializeArray();
PHP
$userList = $_POST['userList'];
for($i=0;$i<sizeof($userList);$i++)
{
$userID = $userList[$i][value] ;
//Insert $userID to DB
}
You may be looking for .serialize
A more generic solution would be to have a form with all the parameters and then serialize it.
Try the following:
var selectedItems = [];
$('#somediv input[type="checkbox"]:checked').each(function () {
selectedItems .push($(this).val());
});
var postData = { "str": str, "arr": selectedItems };
$.ajax({
type: "POST",
url: "/somephpfile.php",
data: postData,
traditional: true,
success: function (data) {
...
}
});
PS I'm assuming you know about serialize and it's not right for your scenario. Definitely check that out first (although it will serialize the whole element). This means if your checkboxes don't have the same NAME attribute or you need to control the variable name they are passed in as you can use my suggestion to do it manually.