javascript takes variable in php form wrong.

Asked

Viewed 78 times

1

I have this script and this form populated in php, I would like to use the delete button to send the name of the training to be deleted. The problem is that javascript always receives the value (training name) of the first row table, even on other buttons. When I use the inspect on the loaded page, each button has its correct value, but the value is always the first line. (yes I am using some obsolete php functions, this is not the issue).

$(function($) {
	// Quando o formulário for enviado, essa função é chamada
	$("#formulario").submit(function() {
		// Colocamos os valores de cada campo em uma váriavel para facilitar a manipulação
		var nometreino = $("#nometreino").val();
     var resposta = confirm("Deseja mesmo deletar? " +nometreino);
 
     if (resposta == true) {

		// Fazemos a requisão ajax com o arquivo envia.php e enviamos os valores de cada campo através do método POST
		$.post('cadastro/remover_treino.php', {nometreino: nometreino }, function(resposta) {
				// Quando terminada a requisição
				// Exibe a div status
				$("#status").slideDown();
				// Se a resposta é um erro
				if (resposta != false) {
					// Exibe o erro na div
					$("#status").html(resposta).fadeOut(4000);
                    setTimeout(function () { location.reload(1); }, 3000);
				} 
				// Se resposta for false, ou seja, não ocorreu nenhum erro
				else {
					// Exibe mensagem de sucesso
					$("#status").html("Apagado! " +nometreino).fadeOut(3000);
                    setTimeout(function () { location.reload(1); }, 3000);  
					// Limpando todos os campos
					$("#nometreino").val("");
					$("#mensagem").val("");
				}
		});
     }
	});
    
});
body role="document">
      
       <form method="post">  
<div class=""><br>
<br>
    </div>
      </form>
       <div class="container theme-showcase" role="main">      
      <div class="page-header">
        <h1>Gerenciar Treinos</h1>
      </div>
      <div class="row">

          <form method="post">
            <div class="form-group">
              <label class="">Selecione a matrícula:</label>
              <div class="">
                <div class=""> <i class=""></i>
                  <form action = "" method="post">
		<?php
		include 'sel_matricula_treinos.php';
		?>
		    
<button type="submit" onClick="" class="" >Selecionar</button>
                    </form>
                </div>
              </div>
            </div>
          </form>
          </div>
          
          
<p>&nbsp;</p>
            
<?php
      $matricula = @$_POST['matricula'];

		$resultado=mysql_query("SELECT distinct (nometreino), ativo, alteracao FROM treinos WHERE idmatricula='$matricula'");

?>	
 <form action="javascript:function()" method="post"  id="formulario"> 
     <center><div id="status"></div> </center>
     
          <table class="table">
            <thead>
              <tr>
                <th>Nome do treino (<?php echo $matricula;?>)</th>
                <th>Data de cadastro</th>
                  <th>Status</th>
                  <th>Apagar</th>
                  

              </tr>
            </thead>
            <tbody>
				<?php 
					while($linhas = mysql_fetch_array($resultado)){
                        $ativo=$linhas['ativo'];
                        $nometreino=$linhas['nometreino'];
						echo "<tr>";
							echo "<td>",$nometreino,"</td>";
                        
                        echo "<td>"; 
                             echo date_format(new DateTime($linhas['alteracao']), "d/m/Y");                                
                        echo "</td>";

                        echo "<td>"; if ($ativo == 1) { echo "Ativo";} 
                        else {echo "Inativo";}
                        
                        echo "<td>"; ?>
                
                 <input type="hidden" name="nometreino" id="nometreino" value="<?php echo $nometreino?>">
<input type="submit" value="Apagar">
                
                    <?php
                        echo $nometreino;
                        
                        echo "</td>";
						 echo "</tr>";
					}

				?>
                       
            </tbody>
              
              
              
          </table>
</form>
      </div>
    </body>

  • 1

    Javascript is not directly receiving php values, it is fetching html, which was built in php. And this search is being done with .val(), here: var nometreino = $("#nometreino").val(); when that nometreino comes from a td : echo "<td>",$nometreino,"</td>";, which is not correct. Instead use .html(). .val() is to be used in <input>, <select> e <textarea> documentation

  • Can I send the source code? Right click > display source code

  • the delete form has to be in the loop, it will not work multiple buttons and lines within the same form

1 answer

0


In HTML, replace:

<input type="submit" value="Apagar">

For

<button type="button" class="apagar" value="<?=$nometreino?>">Apagar<button>

In Javascript, replace:

// Quando o formulário for enviado, essa função é chamada
$("#formulario").submit(function() {
    // Colocamos os valores de cada campo em uma váriavel para facilitar a manipulação
    var nometreino = $("#nometreino").val();

For:

// Quando a ação de apagar for executada.
$(".apagar").on("click", function(e){
// Recebe o identificador do treino especificamente.
var nometreino = $(e.target).val();

If it works, send me a confirmation and if you want I explain to you why it wasn’t working before blz?

  • Friend, it worked. Thank you very much, at night I glue the code working. The error was happening because the java script picked up the value before I clicked, this ?

  • The problem was in the call $("#training"). val();

  • Which is inside a loop, where there are several inputs with the same id, so it always selects the first one

Browser other questions tagged

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