Take the value of the <tr> the user clicked on a dynamic table

Asked

Viewed 1,156 times

0

Hello...

I’ve had a problem for many days and I can’t fix it.

The situation is as follows: I have a table that is created dynamically from the existing data in the database:

Tela de Busca

When the user hovers over an option, it is highlighted:

Tela de busca com opcao selecionada

I need that when clicking on a selected row, I get the value corresponding to the column Name, and can for example put this value in a variable for future treatments.

The big problem is that I do not understand a way to do this in a table that is dynamic, that is, its content varies according to the data of what is being returned from the database.

I need this variable in PHP, I will send its value to another page

Below is the code where all processes occur:

<html>
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="img/bus-coor.png">
    <link rel="stylesheet" href="/css/style.css">
    <title>Buscar Coordenador</title>
</head>
<body>
<form class="registro form" method="get">
    <fieldset><legend>BUSCAR COORDENADOR</legend>
        <label class="labels" for="cNomCoo">Nome </label>
        <input type="text" name="tNomCoo" id="cNomCoo">
        <br>
        <input type="submit" onclick="criarVariavel();" value="Buscar">
    </fieldset>
</form>
<script>
    function criarVariavel() {
        <?php
        $nome_coo = $_GET['tNomCoo'];
        ?>
    }
</script>
</body>
</html>

<?php
include ('configBD.php');

if(!empty($nome_coo)){ // se a varivel tiver valor
// cria a instrução SQL que vai selecionar os dados
    $query = ("SELECT idCoo, tNomCoo, tEma, tTel, tFun FROM coordenador WHERE tNomCoo LIKE '%".$nome_coo."%'");
// executa a query
    $dados = mysqli_query($conexao, $query) or die(mysqli_error());
// transforma os dados em um array
    $linha = mysqli_fetch_assoc($dados);
// calcula quantos dados retornaram
    $total = mysqli_num_rows($dados);
}
else { // se a varivel não tiver valor seleciona retorna todos os dados
// cria a instrução SQL que vai selecionar os dados
    $query = sprintf("SELECT * FROM coordenador ");
// executa a query
    $dados = mysqli_query($conexao, $query) or die(mysqli_error());
// transforma os dados em um array
    $linha = mysqli_fetch_assoc($dados);
// calcula quantos dados retornaram
    $total = mysqli_num_rows($dados);
}
?>

<html>
<head>
    <meta charset="UTF-8">
    <title>Resultado da Pesquisa</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
<table style="font-weight: bolder; text-align: center">
        <td style="border-bottom: 1px solid #5e5e5e; alignment: center; padding: 2px;">ID</td>
        <td style="border-bottom: 1px solid #5e5e5e; alignment: center; padding: 2px; width: 30%; overflow: auto;">Nome</td>
        <td style="border-bottom: 1px solid #5e5e5e; alignment: center; padding: 2px; width: 30%; overflow: auto;">E-mail</td>
        <td style="border-bottom: 1px solid #5e5e5e; alignment: center; padding: 2px; width: 20%; overflow: auto;">Telefone</td>
        <td style="border-bottom: 1px solid #5e5e5e; alignment: center; padding: 2px; width: 30%; overflow: auto;">Categoria Funcional</td>
    </tr>
</table>
<?php
// se o número de resultados for maior que zero, mostra os dados
if($total > 0) {
    // inicia o loop que vai mostrar todos os dados
    do {
        ?>
        <table style="border-spacing: 0px; text-align: center;">
            <tr style="cursor: pointer; border-radius: 3px;" onclick="selecionaLinha" onMouseOver="javascript:this.style.backgroundColor='#75ee83'" onMouseOut="javascript:this.style.backgroundColor=''">
                <td id="cNomCoo" class="celula" style="border-bottom: 1px solid #5e5e5e; alignment: center; padding: 7px;"><?=$linha['idCoo']?></td>
                <td class="celula" style="border-bottom: 1px solid #5e5e5e; padding: 2px; width: 30%; overflow: auto;"><?=$linha['tNomCoo']?></td>
                <td class="celula" style="border-bottom: 1px solid #5e5e5e; padding: 2px; width: 30%; overflow: auto;"><?=$linha['tEma']?></td>
                <td class="celula" style="border-bottom: 1px solid #5e5e5e; padding: 2px; width: 20%; overflow: auto;"><?=$linha['tTel']?></td>
                <td class="celula" style="border-bottom: 1px solid #5e5e5e; padding: 2px; width: 20%; overflow: auto;"><?=$linha['tFun']?>
            </tr>
            <br>
        </table>
        <?php
        // finaliza o loop que vai mostrar os dados
    }while($linha = mysqli_fetch_assoc($dados));
}// fim do if
?>
</body>
</html>
<?php
// tira o resultado da busca da memória
mysqli_free_result($dados);
?>

  • But you want to put the value in a variable javascript is this ? Is that in your question I see almost no javascript and only see almost php.

  • You can edit the question by clarifying whether you want the variable in javascript or php?

  • The variable has to be in PHP, edited question, thank you.

  • 1

    Young, "dynamic" is when you change an element or several elements after the page is rendered, and this is done with Javascript. That is, your table is not dynamic because it comes ready from PHP.

  • 1

    There is no way to save an element value to be used later in PHP. PHP runs on the server and the rendered page runs in the browser. What you can do is use Ajax and create a SESSION to save the value and then pull via PHP. Or save this value in a cookie via Javascript and then pull the JS itself.

  • So if I understood well this code would serve for example only for a query in the database, how is one of its functions, a visualization of what is in the database, and for me to get the value of some line of this I would have to use Ajax creating a SESSION? I’m sorry because I’m a beginner in web language so my doubts seem so elementary.

  • @Carloseduardosilva You can pass a value to another page through a parameter in the URL.

  • @Valdeirpsr the question is how rsrs

Show 3 more comments

1 answer

0

"I need that by clicking on a selected row, I get the value corresponding to the column Name, and can for example put this value in a variable for future treatments."

Taking the value of idCoo and leading to a $result variable on the server side of php for execution at the moment of the click, and we will also Lear to a variable that can be reused later (Session)

Let’s split into two files, the first one (you’re working on) and the second is php where you will save the variable with content.

In the first file:

Before the table code, put this:

<script>
function pegacampo_ajax($val) {
 var dado = $('#idCooDiv'+$val).html(); //pega o texto do div pelo id
 var link = "pegacampo_ajax.php"; //endereco do segundo arquivo php
 $.ajax({type: 'POST', url: link, data: dado, processData: false, contentType: false }).done(function (result) {
 $('#resultado').html(result);
 $('#resultado').css('display', 'block');
});
  return false;
}
</script>

Edit this part in your table:

<td id="cNomCoo">
 <div style="height:50px;width:100px;color:red;font-weight:600;" onclick="pegacampo_ajax('idCooDiv<?=$linha['idCoo']?>')" id="idCooDiv<?=$linha['idCoo']?>">
  <?=$linha['idCoo']?>
 </div>
</td>

Shows the result (place below the table):

<div id="resultado" style="color:red;font-weight:600;width:100px;height:50px;"></div>

In the second file, named pegacampo_ajax.php

On it you write:

<?php
function pegacampo_ajax(){
if (isset($_POST['dado'])){
$resultado = "$_POST['dado']";

//nesta linha tu pode salvar o dado numa session do php
//vou deixar em branco para voce fazer

}
else{
$resultado = "Não há conteúdo";
}
return $resultado;
}

$resultado = pegacampo_ajax();
echo $resultado;

?>

The big problem is I don’t understand a way to do that in table that is dynamic, that is, its content varies according to the data of what is being returned from the database

Ready, if you do not understand so ask someone to edit my answer to Oce with the final code, but this is instead of taking the name, get the id.

I didn’t, there might be a mistake

To change just change the text inside the div and the value will change, you can use the name, or whatever you want

The cat jump is to concatenate the id that comes from the bank with the id of the div to be unique

I concatenei the id that comes from the database along with the id of the div, making it unique, and then, you click, take the value of it via ajax, without repeating, because the name is id="name+id", the id always different.

Browser other questions tagged

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