Welcome Guest, Not a member yet? Register   Sign In
Pass checkbox values into an array using ajax
#1

[eluser]dlm1897[/eluser]
I am needing some help passing checkbox values into an array using ajax and retrieving the values in my controller to execute a query. The code below does not work.

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:

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

My jquery:

Code:
$("#Send_Invite").click(function() {
    var form_data = {
        Opportunity_Id: $('#Opportunity_Id').val(),
        Educator_Id: $('#Educator_Id').val(),
        Educator_Classes: $('[name="Educator_Classes[]"]').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:

Code:
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;
}
#2

[eluser]CroNiX[/eluser]
Did you try just serializing the form?
Code:
var form_data = $("#theForm').serialize();

If you want to add things to your postdata that aren't in the form, you can just append them.
Code:
var form_data = $("#theForm').serialize() + '&ajax=1';
#3

[eluser]dlm1897[/eluser]
Sure enough, that worked!

Is it more efficient to simply serialize the form like this? The reason I didn't to begin with was due to the elements being a part of a large multi-step form. So, there are a lot of additional elements in the form that I do not need for this request.

Thanks!
#4

[eluser]CroNiX[/eluser]
I'm not totally sure. I just know the docs for serialize() only reference working on a form object directly and not individual form control elements.

If you have multiple forms, in the past I've submitted both forms by concatenating them so it might work for your purpose as well.
Code:
var formData = $('#form1').serialize() + '&' + $('#form2').serialize() + '&ajax=1';

If you don't need to "use" all form elements submitted, you can just ignore them in the controller and only use the ones that you do.
#5

[eluser]CroNiX[/eluser]
Also, just a FYI, you can tell if a request is made by AJAX by:
Code:
if ($this->input->is_ajax_request())
{
  //this was submitted with ajax
}




Theme © iAndrew 2016 - Forum software by © MyBB