Fill in a div when selecting a select item (form)

2

Colleagues.

I have a select from which the data comes from a database. See:

public function verSelect($tabela,$idTB,$nomeTB,$nomeSelect){

        $query = "SELECT * FROM ".$tabela;
       // echo $query;
        $sqlSelect = mysqli_query($this->conexao,$query);

        $select = "<select name='".$nomeSelect."' class='form-control' id='selecionar'>";
        $select .= "<option value='selecione'>Selecione</option>";    
        while($jmSelect = mysqli_fetch_object($sqlSelect)){
            $select .= "<option value='".$jmSelect->$idTB."'>".$jmSelect->$nomeTB."</option>";
        }
        $select .= "</select>";

        return $select;

    }

Cool, cool, so far so good. However I need to make when selecting an item from this select, a div appears with the contents of another table that is already related. For example: Let's suppose that I choose Fernando Pessoa in this select, would automatically appear the div with the word poet from another table.

Remember that the table already exists and is populated with the information, I only need the mechanics in Javascript or jquery on how to do this.

    
asked by anonymous 19.10.2016 / 20:44

1 answer

2

You would need to make an ajax request for a PHP script with the information the user chooses in select!

This script will capture the value that the user chooses in select:

$('#selecionar').change(function() {
    var selectedItem = $(this).val();
    // Requisição ajax
    $.ajax({
       type: "GET",
       url: "/url-para-obter-dados",
       data: {item: selectedItem},
       dataType: "json",
       success: function (response) {
           // Aqui você pode montar o outro select a partir dos dados que vierem na variável response.
           console.log(response);
       }
   });
});

Note, where it is written '/ url-to-get-data', you replace with the URL you will make the operation in the database, in PHP you will be able to access the selected item using $ _GET ['item' ]. It is important that you return the database data as a json, so use the json_encode of PHP.

Read more about the ajax request here: link

    
19.10.2016 / 20:54