Get select value and use it in the same php file

2

Hello good morning I have this code is to fill a select with php and mysql but with the value obtained I must make another query to fill the other select depending on the selection of the first, I need to do it in the same file to fill other inputs that I must add from the database query, I hope you can support me to get in a variable the selected value of the first select, then my code:

<form method="post" accept-charset="UTF-8" name="reporte">
    <ul >
        <li >
            <label for="proveedor">Proveedor del Servicio: </label> 
                <select id="proveedor" name="proveedor">
                       <option value="" disabled selected>Seleccione Proveedor de Servicio</option>
                <?php

                    $mysqli = new mysqli('localhost', 'prueba', '123456', 'intranet_soporte_bitacora');
                    $mysqli->set_charset("utf8");
                    $query = $mysqli -> query ("SELECT * FROM proveedores");
                        while ($valores = mysqli_fetch_array($query)) {
                            echo '<option value="'.$valores[proveedor].'">'.$valores[proveedor].'</option>';
                                            }
                ?>
        </select></li>
            <li>

            <label for="usuarios">Usuario: </label>
                <select id="usuarios" name="usuarios">
                    <option value="" disabled selected>Seleccione Usuario que Recibirá el Servicio</option>
                     <?php
                        $mysqli = new mysqli('localhost', 'prueba', '123456', 'intranet_soporte_bitacora');
                        $mysqli->set_charset("utf8");
                        $query = $mysqli -> query ("SELECT * FROM empleados ORDER by usuario");
                        while ($valores = mysqli_fetch_array($query)) {
                            echo '<option value="'.$valores[usuario].'">'.$valores[usuario].'</option>';
                        }
              ?>
            </select></li>
            </ul>
</form>
    
asked by Harrison Olvera 24.04.2018 в 17:33
source

1 answer

0

I explain what happens. You need to open an AJAX connection that is a "tunnel" to the back-end to bring in information without having to reload the page completely. I gave you an example using JS / Jquery, maybe I have a couple of syntax errors because I do not have the correct development environment. However, debugging should be easy for you. I documented to you that it does everything and I separated your PHP code from USERS, an annex that, your query to your users may be but it should not be complicated for you because you know how it works.

YOUR HTML should look more or less like this.

<form method="post" accept-charset="UTF-8" name="reporte">
    <ul >
        <li >
            <label for="proveedor">Proveedor del Servicio: </label> 
                <select id="proveedor" name="proveedor">
                       <option value="" disabled selected>Seleccione Proveedor de Servicio</option>
                <?php

                    $mysqli = new mysqli('localhost', 'prueba', '123456', 'intranet_soporte_bitacora');
                    $mysqli->set_charset("utf8");
                    $query = $mysqli -> query ("SELECT * FROM proveedores");
                        while ($valores = mysqli_fetch_array($query)) {
                            echo '<option value="'.$valores[proveedor].'">'.$valores[proveedor].'</option>';
                                            }
                ?>
        </select></li>
            <li>

            <label for="usuarios">Usuario: </label>
                <select id="usuarios" name="usuarios">

                </select></li>
            </ul>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  //Función que indica que el documento está listo
  $(function(){ 

    //Detectar el cambio de opción del proveedor
    $(document).on('change','#proveedor',function(){

      //borrar las opciones que están cargadas en los usuarios
      $('#usuarios option').each(function(){
        $(this).remove();
      });

      //Guardar valor seleccionado
      var proveedor = $(this).val();

      //Validar que no esté vacío o nulo
      if( proveedor && proveedor != '' ){

        //Abrir conexión de AJAX
        $.ajax({
          url: 'buscaUsuario.php', //URL donde está el archivo que busca a los usuarios
          method: 'GET', //Verbo de petición del protocolo
          data: {proveedor:proveedor}, //Información que se enviará al PHP
          success:function(respuesta){
            //Respuesta satisfactoria

            //Validar si se creó correctamente el JSON
            if( respuesta.success ){
              var i = 0;

              //Agregar opción por default a usuarios
              $('#usuarios').append('<option disabled selected>Seleccione Usuario que Recibirá el Servicio</option>');

              //Recorrer el nodo de información recopilada
              for (i; i < respuesta.data.length;) {

                //Armar la opción y agregarla al SELECT de usuarios
                let option = '<option value="' + respuesta.data[i].id + '">' + respuesta.data[i].usuario + '</option>';
                $('#usuarios').append(option);
                i++;
              }      

            }

            else{
              alert( respuesta.message );
            }
          },
          error:function(err){
            alert( err );
          }
        })
      }

    });

  });
</script>

NOW YOUR PHP THAT YOU MUST NAME searchUser.php AT THE SAME LEVEL THAT YOUR HTML

<?php

  //Agregamos el encabezado para retornar JSON
  header('Content-Type: application/json');

  //Abrimos la conexión a la DB
   $mysqli = new mysqli('localhost', 'prueba', '123456', 'intranet_soporte_bitacora');
   $mysqli->set_charset("utf8");

   //Declaramos un arreglo que vamos a retornar
   $arr = array();

   //Validamos que la información que llega no esté vacía,
   //armamos un arreglo asociativo que tendrá la información de retorno
   if( empty($_REQUEST['proveedor']) ){
     $arr = array(
       'success' => false,
       'message' => 'El valor llegó vacío',
       'data' => null
     );
   }

   else{

     //Asignamos el valor que llegó a una variable y hacemos la consulta
     $id = $_REQUEST['proveedor'];
     $sql = "SELECT * FROM empleados ORDER by usuario WHERE proveedor_id = " . $id;

     //Validamos que la consulta esté bien creada
     if( !$r = mysqli_query( $mysqli, $sql )){
       $arr = array(
         'success' => false,
         'message' => 'Consulta mal formada',
         'data' => null
       );
     }

     else{
       //Validamos que la consulta regrese información
       if( mysqli_num_rows( $r ) <= 0 ){
         $arr = array(
           'success' => false,
           'message' => 'La consulta no regresó registros',
           'data' => null
         );
       }

       else{
         //Recorremos la variable para extraer la información y la metemos
         //en un arreglo asociativo que se usara en el Javascript
         $data = array();
         while ($rw = mysqli_fetch_array( $r )) {
           $data[] = array(
             'id' => $rw['id'],
             'usuario' => $rw['usuario']
           );
         }

         //Agregamos la variable al nodo data y ponemos todo exitoso
         $arr = array(
           'success' => true,
           'message' => 'Consulta exitosa',
           'data' => $data
         );
         //Limpiamos la el resultado y liberamos memoria
         mysqli_free_result($r);

        //Cerramos la conexión
        mysqli_close($mysqli);
       }         
     }
   }

   //Retornamos el arreglo con un formato de tipo JSON
   echo json_encode( $arr );
?>
    
answered by 24.04.2018 в 18:49