AJAX PHP pass select value to a codeigniter controller

0

I have a problem about which I am very confused. I have a dynamically generated selection box using a php query with codeigniter:

<div class="form-group">
  <select onchange="func(this.value)">
    <option value="">Seleccione</option>
    <?php foreach ($array as $id=>$nombre) echo '
    <option value="',$id,'">',$id.' '.'('.$nombre.')','</option>'; ?>
  </select>
</div>

<div id="listaPersonal"></div>
I'm completely new to AJAX, but I need to use jQuery and Ajax to pass the variable this.value to a controller for use in a later query.

Here is my script: the code that I have in the answer of ajax is the following layout in a table the result that I send to a div in the html view

<script>
function func(selectedValue)
 {
    $.ajax({
        url: "http://localhost/sis/personal/mostrar",
        type: 'POST',
        data: {option : selectedValue},
        success: function(respuesta) {
            
         var registros = eval(respuesta);
    
        html ="<table><thead>";
        html +="<tr><th>ID</th><th>apellidos</th><th>dni</th><th>telefono</th></tr>";
        html +="</thead><tbody>";
        for (var i = 0; i < registros.length; i++) {
            html +="<tr><td>"+registros[i]["id_personal"]+"</td><td>"+registros[i]["apellidos"]+"</td><td>"+registros[i]["dni"]+"</td><td>"+registros[i]["telefono"]+"</td></tr>";
        };
        html +="</tbody></table>";
        $("#listaPersonal").html(html);
          
        }
    });
}
</script>

This is the query that I have the model that receives a parameter that is just the one I want to get the select

function consulta($valor){
		$this->db->select('id_personal, apellidos, dni , telefono');
		$this->db->from('personal');
		$this->db->WHERE('personal.id_personal', $valor); 
		$consulta = $this->db->get();
		return $consulta->result();
	}
    
asked by Fernando Banegas 05.01.2017 в 00:16
source

2 answers

1

To obtain data in the controller that has been sent through ajax, the object input of CI_Controller is accessed. Through this object you can get the values sent.

$this->input->post("option");

Your query would be like this:

function consulta(){
        $selectedOption = $this->input->post("option");
        $this->db->select('id_personal, apellidos, dni , telefono');
        $this->db->from('personal');
        $this->db->where('personal.id_personal', $selectedOption); 
        $consulta = $this->db->get();
        return $consulta->result();
}

On the line:

$selectedOption = $this->input->post("option");

It's where we get the value for the option key that you sent by ajax.

    
answered by 05.01.2017 в 00:40
0

The method you use in ajax is POST,

.
.

$valor = $_POST['option'];
$resultado = $this->mimodelo->consulta($valor);

where option is the name you are placing in

data:{option:selectedValue}
    
answered by 05.01.2017 в 00:38