Viewed   956 times

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!

 Answers

4
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

Friday, November 4, 2022
3

Got it!

To properly access the JavaScrtipt objects in PHP I need to JSON.stringify them when pushing on the array. Then, on PHP, json_decode them to a PHP object, and access their properties with the '->' operator.

The final solution is as follows:

<?php 
include 'ChromePhp.php';

if (isset($_POST['newUsers'])) {

    $newUsers = $_POST['newUsers'];

    foreach ($newUsers as $user) {
        # code...
        $usr = json_decode($user);
        ChromePhp::log("Nome: " . $usr->nome . " - Idade: " . $usr->idade);
    }

} else { ?>

<html>
<body>

    <script src="js/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
        //var newUsersObj = {};
        var newUsers = [];

        newUser = {};
        newUser['nome'] = 'alvaro';
        newUser['idade'] = '34';
        newUsers.push(JSON.stringify(newUser));

        newUser1 = {};
        newUser1['nome'] = 'bia';
        newUser1['idade'] = '7';
        newUsers.push(JSON.stringify(newUser1));

        newUser2 = {};
        newUser2['nome'] = 'alice';
        newUser2['idade'] = '2';
        newUsers.push(JSON.stringify(newUser2));

        $.ajax({
            url: "testcookie.php",
            type: "POST",
            data: {
                'newUsers[]': newUsers
            },
            success: function () {

            },
            error: function () {

            }
        });

    </script>
</body>
</html>
<?php } ?>
Thursday, December 22, 2022
 
jonvd
 
5
if ($("#yourCheckboxID").is(":checked")) {  
    // checkbox is checked 
} else {
    // checkbox is not checked 
}

will do the job.

Monday, November 21, 2022
 
kachi
 
3

i think your problem may be in ajax code since you are using formData object . try append the message variable with it

$('#submit').on('click', function(){

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);
  fd.append('message ',$('#message').val());

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: fd,  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});
Saturday, November 12, 2022
 
malina
 
1

To upload multiple images use array:

<input type="file" id="attachments" name="attachments[]" multiple>

and send the form data using ajax:

 var formData = new FormData(this);
$.ajax({
    url: "submit.php",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function(result){

    // do something
   }
});

In php file use a loop( foreach i recommend) to save all attachments.

foreach($_FILES['attachments']['name'] as $key=>$val){

// do whatever you want

}
Tuesday, August 23, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :