How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){ $.post("ajax.php", { selectedcheckboxes:user_ids, confirm:"true" }, function(data){ $("#lightbox").html(data); }); }
and this is my form
<form> <input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' /> <input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' /> <input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' /> <input name="confirm" type="button" value="confirm" onclick="submit_form();" /> </form>
$myField = htmlspecialchars( $_POST['myField'] ) ); if( isset( $_POST['myCheckboxes'] ) ) { for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ ) { // do some stuff, save to database, etc. } } // create the response $response = 'an HTML response'; $response = stripslashes($response); echo($response);
Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []}; $(":checked").each(function() { data['user_ids[]'].push($(this).val()); }); $.post("ajax.php", data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With