Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple checkboxes using jQuery ajax post

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> 
like image 922
ahmed Avatar asked May 26 '09 02:05

ahmed


People also ask

How to post multiple checkbox value in ajax?

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

How to pass multiple checkbox value in jQuery?

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.


1 Answers

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); 
like image 126
Paul Tarjan Avatar answered Sep 20 '22 08:09

Paul Tarjan