简体   繁体   中英

Pass checkbox values into an array using ajax to php

I am needing some help passing checkbox values into an array using ajax and retrieving the values in my controller. The following code is not working. I receive the error: "Invalid argument supplied for foreach()". Var_dump gives string(42) "Educator_Classes[]=1&Educator_Classes;[]=3

Thanks for any help you can provide.

My html form input:

<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>

My jquery:

$("#Send_Invite").click(function() {
    var form_data = {
        Opportunity_Id: $('#Opportunity_Id').val(),
        Educator_Id: $('#Educator_Id').val(),
        Educator_Classes: $('#Educator_Classes:checked').serialize(),
        ajax: '1'
    };

    $.ajax({
        url: "<?php echo site_url('schedule/update_educator_class'); ?>",
        type: 'POST',
        data: form_data,
        success: function(data) {
            $('#response').html(data);
        }
    });

    return false;
})

My controller:

function update_educator_class() {
    $Educator_Id = $this->input->post('Educator_Id');
    $Opportunity_Id = $this->input->post('Opportunity_Id');
    $Educator_Classes = $this->input->post('Educator_Classes');

    foreach($Educator_Classes as $Educator_Class):
        $this->ion_auth_model->update_educator_class($Opportunity_Id, $Educator_Class, $Educator_Id);
    endforeach;
}

The Solution is that you have to take the array of name attribute of checkbox. Like :

<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>

You have to use [] for name attribute and not for id , otherwise it can't act like an array

<input type="checkbox" id="Educator_Classes" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>

And also your jQuery code can be simpler:

$("#Send_Invite").click(function() {
    var form_data = $(this).closest('form).serialize();
    form_data['ajax'] = 1;

    $.ajax({
        url: "<?php echo site_url('schedule/update_educator_class'); ?>",
        type: 'POST',
        data: form_data,
        success: function(data) {
            $('#response').html(data);
        }
    });

    return false;
});

To debut what's passed to $Educator_Classes you can do this:

var_export($Educator_Classes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM