Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send multiple checkbox data to PHP via jQuery ajax()

Tags:

I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:

The HTML:

<form method="post" action="myurl.php" id=myForm>     <textarea id="myField" type="text" name="myField"></textarea>     <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />     <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />     ...(maybe some more checkboxes - dynamically generated as necessary)     <input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" /> </form> 

The jQuery:

function submitForm() { $(document).ready(function() { $("form#myForm").submit(function() {          var myCheckboxes = new Array();         $("input:checked").each(function() {            myCheckboxes.push($(this).val());         });          $.ajax({             type: "POST",             url: "myurl.php",             dataType: 'html',             data: { myField:$("textarea[name=myField]").val(),                     myCheckboxes:myCheckboxes },             success: function(data){                 $('#myResponse').html(data)             }         });         return false; }); }); 

Now, the PHP

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

Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!

like image 367
John Anderson Avatar asked Feb 29 '12 04:02

John Anderson


People also ask

How to pass multiple checkbox value in ajax jQuery in PHP?

$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 can I send multiple checkbox values in Ajax?

<? php $errorMSG = ""; // Company Name if (empty($_POST["company_name"])) { $errorMSG = "Name is required "; } else { $company_name = $_POST["company_name"]; } // Contact Name if (empty($_POST["contact_name"])) { $errorMSG .

How can I send multiple checkbox values in PHP?

Read Multiple Values from Selected CheckboxesUse the foreach() loop to iterate over every selected value of checkboxes and print on the user screen. <? php if(isset($_POST['submit'])){ if(! empty($_POST['checkArr'])){ foreach($_POST['checkArr'] as $checked){ echo $checked.

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.


2 Answers

Yes it's pretty work with jquery.serialize()

HTML

<form id="myform" class="myform" method="post" name="myform"> <textarea id="myField" type="text" name="myField"></textarea> <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" /> <input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" /> <input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" /> </form>  <div id="myResponse"></div> 

JQuery

function submitForm() { var form = document.myform;  var dataString = $(form).serialize();   $.ajax({     type:'POST',     url:'myurl.php',     data: dataString,     success: function(data){         $('#myResponse').html(data);       } }); return false; } 

NOW THE PHP, i export the POST data

 echo var_export($_POST); 

You can see the all the checkbox value are sent.I hope it may help you

like image 192
Winn Minn Soe Avatar answered Oct 24 '22 07:10

Winn Minn Soe


var myCheckboxes = new Array(); $("input:checked").each(function() {    data['myCheckboxes[]'].push($(this).val()); }); 

You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push

like image 45
TomaszSobczak Avatar answered Oct 24 '22 08:10

TomaszSobczak