Search data with JSON

Asked

Viewed 193 times

-1

I need, through a <select> </select>, bring the data to some input[type='text']. I believe it is through JSON and AJAX, because the page can not have any "Submit".

For example:

I have a <select> </select> to select a student from my classroom, and some input[type='text'] to bring the data of the selected student, such as "age", "room number", "mother’s name", "father’s name", among others. The page may not have submit as I have more than one <select> </select> that will play the same role (when selecting an item, it will be displayed in input[type='text'] the characteristics of it). The form that I was able to develop makes it possible to bring the data of one or the other <select> </select>.

I hope you have understood my problem. I am inexperienced in JS.

Code in PHP:

<?php $query="SELECT idFunc AS 'ID', nomeFunc AS 'NOME', idadeFunc AS 'IDADE' FROM funcionario WHERE statusFunc = '1' ORDER BY nomeFunc"; ?>

<form method="GET" action="">
    <select name="aluno" onclick="if (this.value != ''){this.form.submit()};">
        <option value="">- ALUNOS -</option>

<?php   $sql =  odbc_exec($con, $query);

        $i=0; 
        while(odbc_fetch_row($sql)){

            $id=odbc_result($sql,"ID");
            $nome=odbc_result($sql,"NOME");
            $idade=odbc_result($sql,"IDADE");

            $i++;
?>
        <option value="<?php echo $id; ?>" ><?php echo $nome; ?></option>
<?php   
        } odbc_close($con); 
?>
    </select>
</form>

In PHP, I was able to do what I wanted, but when I select another checkbox, it deletes the first result and displays the results of the second. I could make the user select the two items and after doing a Submit, the information would appear, but I want to make a system more intuitive, where the user just select and appear in real time for it.

Upshot:

inserir a descrição da imagem aqui

Upon any doubt or observation, I am at your disposal.

  • the ideal is to try to do, so we can go helping you. If you already have something done, edit and post the code.

  • Leave it, I’ll change it.

1 answer

0


Do you already have the web service in your PHP? Making an asynchronous request (AJAX) with jQuery or Axios is easier, but you can also use native solutions like fetch.

function ajax(id) {
    return fetch(`/meuWebservice?id=${id}`).then(r => {
        if (r.ok) return r.json();
        throw r.text();
    });
}

So in your PHP you would have something like

public function meuWebservice() {
    $id = $_GET['id'];
    $query = "SELECT * FROM {/*sua tabela*/} WHERE idAluno = '$id'";
    $sql =  odbc_exec($con, $query);
    odbc_fetch_row($sql);

    $retorno = [];
    $retorno['resultado'] = [
        'idade' => $nome=odbc_result($sql,"IDADE"),
        'numero_da_sala' => $idade=odbc_result($sql,"NUMEROSALA"),
        'nome_mae' => $idade=odbc_result($sql,"NOMEMAE"),
        'nome_pai' => $idade=odbc_result($sql,"NOMEPAI")
    ];

    odbc_close($con);
    echo JSON_ENCODE($retorno);
    die();
}

Now in Javascript create a function to be called in the select onchange. It can also be an eventListener. Declare the function as async allows us to use await to wait for the fetch response, which is a Promise.

async function buscaInfo() {
    try{
        let {resultado} = await ajax(this.value);
        document.getElementById('idade_aluno').value = resultado.idade;
        document.getElementById('numero_sala').value = resultado.numero_sala;
        document.getElementById('nome_mae').value = resultado.nome_mae;
        document.getElementById('nome_pai').value = resultado.nome_pai;

    } catch (err) {
        console.error('Erro na consulta', await err);
    }   
}

This is all a half-blind example, you’ll need to adjust the elements' ids, tidy up the PHP query, start $con with the correct value.

  • Got it. I really appreciate the help. But when I select the other item, it won’t reset the first Select and perform the second?

  • Can’t you handle it? You can send more information to change, or access this to find out what select is about, and then send the values to the correct inputs.

Browser other questions tagged

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