Load select element with ajax

0

I would like to make a query and collect it both in a text box and in a select. I can capture the query in a text box, but not in the select.

Index.php

<script>
function cargar_energia(){
  //var n =  document.getElementById("nombre").value;
  var datos={
                "nombre": $("#nombre").val(),
              }

        $.ajax({
        type:'post',
        url: 'prueba_consulta.php',
        data: datos,
        dataType: 'json',   
        //data: {nombre:n},
        success: function(d){
           $("#respa").val(d[0]);// ID de la 1era caja de texto
           $("#respa2").val(d[1]); // ID de la 2da caja de texto

            }

        });
        return false;
}
</script>


<form method="post">
  <input type="text" name="nombre" size="30" name="" id="nombre">
  <input type="button" name="" value="enviar" onclick="cargar_energia()">

</form>


  <input type="text" id="respa"><br>
  <select id="respa2"></select>//Aca desearia cargar la otra opcion

test_consulta.php

<?php
//************ conexion a BD ***************
$con = mysql_connect("localhost","root","");
mysql_select_db("mantenimiento",$con);

 $filtro=$_POST["nombre"];
 $rs= mysql_query("SELECT * FROM registro_energia_temp WHERE nombre_site like '%$filtro%' order by id_energia desc ;"); 

$row = mysql_fetch_assoc($rs);
$datos_a_enviar = array($row['nombre_site'], $row['fecha_manto_energia']);
echo json_encode($datos_a_enviar);

?>
    
asked by Javier A. 26.10.2017 в 16:40
source

1 answer

1

To add content to select you must do the following:

<script>
function cargar_energia(){
  //var n =  document.getElementById("nombre").value;
  var datos={
                "nombre": $("#nombre").val(),
              }

        $.ajax({
        type:'post',
        url: 'prueba_consulta.php',
        data: datos,
        dataType: 'json',   
        //data: {nombre:n},
        success: function(d){
           $("#respa").val(d[0]);// ID de la 1era caja de texto
           $("#respa2").html('<option value="'+ d[1] +'">'+ d[1] +'</option>'); // ID de la 2da caja de texto

            }

        });
        return false;
}
</script>

As you can see what you have to do is add a label option to select with the information you want to show, which in this case is the one that returns the request ajax .

    
answered by 26.10.2017 / 16:47
source