Fill Select based on the value of another previous Select

Asked

Viewed 102 times

1

Hello, I would like to enter information that is in a database based on the value that the select is selected.

Based on the value that the 'professional' input had appeared the services that are registered in the database.

I saw some posts using Ajax, Javascript, but I could not adapt to my code, if someone can give a strength. If you need more information just let us know.

Thanks in advance.

<form action="pages/inserts/insertagendamento.php" name="agendamento" method="post">
        
        <label for="data">Data:</label>
        <input id="data" name="data" type="date" min="<?php echo date('Y-m-d'); ?>">
        
        <label for="hora">Hora:</label>
        <input type="time" id="hora" name="hora">
        
        <label for="duracao">Duração:</label>
        <input type="time" id="duracao" name="duracao" placeholder="h:m"><br>
        
        
        <label for="profissional">Profissional:</label>
            <select id="profissional" name="profissional">
            <option =value="">Selecione a Profissional</option>
            <?php
            include ("conexao.php");
            $query = "SELECT * FROM profissionais";
            $pesquisa = mysqli_query($conn, $query);
            
            while($exibe = mysqli_fetch_array($pesquisa)) {
                echo "<option value=" . $exibe["profissionais_id"] . "> ". $exibe["profissionais_nome"] . "</option> ";
            }
            ?>
            </select><br>
            
        <label for="servico">Servico:</label>
            <select id="servico" name="servico">
            <option value="">Selecione o serviço</option>
            
             Aqui seria oq preciso preencher

            </select>
            
        Cliente: <input type="text" name="cliente"><br>
        <input type="submit" value="Cadastrar">
</form>

1 answer

1


opa Raphael, to solve this is quite simple, but you will need a file .php separate waiting for the first select filter.

To do so, you will need to send a request using ajax even, let’s go to javascript:

var selectServicos = document.querySelector('#servico')

var selectProfissional = document.querySelector('#profissional')

selectProfissional.onchange = function(evento){ // função que vai ser executada cada vez que o valor do select for mudado, passando o evento como parametro
    var id_filtro = evento.target.value // pega o valor do evento, que vai ser o do select profissional

    fetch('seu-backend.php?id_filtro='+id_filtro) // faz a requisição para a url, passando o filtro como parâmetro
       .then(response => response.text()) // avisa que a proxima resposta da promise deve ser um texto
       .then(options => selectServicos.innerHTML = options)  // exibe os valores dentro do seu select, que foram retornados do seu backend
}

Ready, with this code snippet you will already send the request to the backend file, now let’s go to it:

$id_filtro = $_GET['id_filtro'];

include ("conexao.php");
$query = "SELECT * FROM sua_tabela WHERE seu_filtro = $id_filtro";
$pesquisa = mysqli_query($conn, $query);

while($exibe = mysqli_fetch_array($pesquisa)) {
    echo "<option value=" . $exibe["valor"] . "> ". $exibe["valor"] . "</option> ";
}
die;

And ready, your code will already work. Remember that die in the end it is necessary, to make sure that there will be no more HTML than we want. Another interesting point is to leave the error_reporting(0) so he doesn’t get in the way of his return.

This code is also kind of vulnerable, since as we are filtering from a given client, someone with more knowledge can try to give an Injection SQL or pass an unwanted value. Then it’s up to you to make a deal.

I hope I’ve helped!! :)

  • Thanks a lot brother, it worked out here, with this code your was much easier to understand (:

  • and as for security without problem, it is a system that I am doing only for 'domestic' let’s say so, but thank you again

  • Ah show then bro! happy to help :)

Browser other questions tagged

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