Send array to Controller and insert into DB, with Ajax and Codeigniter

Asked

Viewed 326 times

1

Hello,

I am unable to receive (in the controller) the array that is sent from a View via ajax. I already tested it in the console.log and the array is sent but nothing happens in the controller.

the input, "numdias" defines the number of inputs with the date to be inserted (the array to be sent to the controller).

Follows the corresponding code:

View:

 <div class="form-group">                               
                                <label>Numero de dias a adicionar:</label>
                                <input type="number" class="form-control" name="numDiasAnuais" id="txtNumDias" min="0"/>

                            </div>
                            <div id="divForm"></div>
                            <template id="tmplLinha">
                                <div class="form-group">                                    
                                <input type="text" name="data[]" id="data" readonly="readonly" class="inserir_data form-control datasIndisponiveis"/>                                
                            </div>
                            </template>                                
                             <div class="form-group">                 
                                <button type="submit" name="submitAddDatasAnuaisIndisponiveis" id="submitAddDatasAnuaisIndisponiveis" class="form-control">Adicionar</button> 
                                <button type="button" class="form-control " data-toggle="modal" data-target="#modaldataindisponiveis">Listar Datas</button>                                    
                            </div>

Ajax:

//dATAS INDISPONIVEIS
$("#submitAddDatasAnuaisIndisponiveis").click(function () {
    event.preventDefault();



    var dataIndisponivel = new Array();        

    $("input.datasIndisponiveis").each(function(){
        dataIndisponivel.push($(this).val());

    })  

    console.log(dataIndisponivel);     


    jQuery.ajax({      

    type: "POST",
    url: "<?php echo base_url('sistema/addDatasIndisponiveis'); ?>",
    dataType: 'json',
    data: {dataIndisponivel},
    success: function(res) {
    if (res)
    {
      $('#mensagensErro').html(res);
      $("#error-dialog").modal("show");          
      //$("input#data").val('');


    }
    }
    });
});

Controller:

// #40
public function addDatasIndisponiveis()
{
    if ($this->session->userdata('logged_in') == true && $this->session->userdata('nivel') == 0) {
        // $this->load->library('form_validation');
        // $this->form_validation->set_rules('data[]', 'Datas', 'required|is_unique[tbldataindisponivel.data]');
        // if ($this->form_validation->run() == false) {

        //     $res = '<div style="color:red;">'.validation_errors().'</div>';
        //     echo json_encode('$res');
        //     exit;


        // } else {
            $datas = $this->input->post('data[]');
            for ($i = 0; $i < count($datas); $i++) {
                $inserir = $this->sistema_model->addDatasIndisponiveis($datas[$i]);
            }
            if ($inserir) {
                $res = '<div style="color:green;">Adicionado com sucesso</div>';
            }else{
                $res = '<div style="color:red;">Erro</div>';
            }

            echo json_encode($res);
            exit;
       // }

    } else {

        redirect('inicio/index', 'refresh');
    }
}
  • 1

    You can’t wear it like that data: {dataIndisponivel}, since dataIndisponivel is an array. Forehead data: {datas: dataIndisponivel}, and then $datas = $this->input->post('datas');. Works?

  • 1

    Sergio, thanks worked, :D

1 answer

2


In ajax you have data: {dataIndisponivel}, which is invalid sitaxe.

An object must have a key and a value {chave: valor} and in this case you lack the key.

So you can change to data: {datas: dataIndisponivel}, in Javascript and switch the controller to $datas = $this->input->post('datas');.

So you pass the same key in ajax as the one you are selecting in the controller.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.