How to UPDATE with AJAX + PHP + PDO

Asked

Viewed 169 times

2

I’m trying to do an Update with AJAX and PDO, but I’m not getting it. I’ve tried several ways and I can’t adjust the code. It is affecting only the last registered id. Can anyone help me please? Follow the code:

function uptade_cat() {
    
    var valor_update=$("#valor_update").val();
    var id_cat_update=$("#id_cat_update").val();
    var nome_categoria_update=$("#nome_categoria_update").val();
 
	var id_cat = $(this).attr("id_cat");
        $.ajax({
            type: "POST",
            url: "caixa/categoria_uptade.php",
            data: {nome_categoria:nome_categoria_update, valor:valor_update, id_cat:id_cat_update},
            dataType: "JSON",
            success: function (data) {
				$('#valor_update').find("input[name='valor_update']").val()
				$('#nome_categoria_update').find("input[name='nome_categoria_update']").val()
				$('#id_cat_update').val(data.id_cat_update);
			 $('#alert_message3').html('<div class="alert alert-success alert-dismissible fade show" role="alert"><strong>Sucesso!</strong> Categoria Atualizado.<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
			$('#categoria_uptade_form').reload(); 

				
            },
            error: function() {
				$('#erro').html('<div class="alert alert-danger alert-dismissible fade show" role="alert"><strong>Erro!</strong> Ocorreu algum problema ao atualizar categoria.<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>');
							
           
            },
        });
  }
<div class="col-lg-12">

 	<div class="card-header">
                                <strong class="card-title">Editar Categoria</strong>
                            </div>
			<div class="card-body">
            <div class="table">
              <table class="table table-striped" style="width:100%">
                <thead>
                  <tr>
                    <th class="td-actions">Registro</th>
                    <th class="td-actions">Categoria</th>
                    <th class="td-actions">Valor</th>
                    <th class="td-actions">Editar</th>
                  </tr>
                </thead>
                <tbody>
<?PHP
$select = "SELECT * from caixa_categoria ORDER BY id_cat DESC ";

		
		try{
			$result = $conexao->prepare($select);			
			$result->execute();
			$contar = $result->rowCount();
			if($contar>0){
				while($mostra = $result->FETCH(PDO::FETCH_OBJ)){
?>           
                  <tr>
					<td> <?php echo $mostra->nome_categoria;?></td>
                    <td> <?php echo $mostra->categoria;?></td>
                    <td> <?php echo $mostra->valor;?> </td>
                    <td class="td-actions text-center"> <a href="" class="btn btn-outline-warning" data-toggle="modal" data-target="#cotegoria_<?php echo $mostra->id_cat;?>"><i class="far fa-edit"></i> Editar</td>
				</tr>
					
<?php
}		
			
			}else{
				echo '<div class"alert alert-danger">
                      <button type="button" class="close" data-dismiss="alert">×</button>
                      <strong>Aviso!</strong> Não há post cadastrado em nosso banco de dados.
                </div>';
			}
			
		}catch(PDOException $e){
			echo $e;
		}
					
		?>			
					           
                  
                
                </tbody>
              </table>
					</div>
				</div>
			</div>


<!-- Modal -->
<?php 

			$result = $conexao->prepare('SELECT * from caixa_categoria');		
			$result->execute();
				while($mostra = $result->FETCH(PDO::FETCH_ASSOC)):
		
?>
<div class="modal fade" id="cotegoria_<?php echo $mostra['id_cat'] ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Categoria: <?php echo $mostra['nome_categoria'] ?> (<?php echo $mostra['categoria'] ?>)</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
		  <form id="categoria_uptade_form" name="categoria_uptade_form">
			  <div class="form-row">
				  <input type="hidden" name="id_cat_update" id="id_cat_update" value="<?php echo $mostra['id_cat'] ?>" > 
				<div class="form-group col-md-6">
				  <label for="inputEmail4">Nome Categoria</label>
				  <input type="text" class="form-control" name="nome_categoria_update" id="nome_categoria_update" value="<?php echo $mostra['nome_categoria'] ?>">
				</div>
				<div class="form-group col-md-6">
				  <label for="inputEmail4">Valor</label>
				  <input type="text" class="form-control" name="valor_update" id="valor_update" value="<?php echo $mostra['valor'] ?>">
				</div>

		</div>
</form>
		 
        <div id="alert_message3"></div>
        <div id="erro"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
		<button type="button" class="btn btn-success" onclick="uptade_cat()">Atualizar</button>

      </div>
    </div>
  </div>
</div>
<?php endwhile; ?>

categoira_uptade.php

$id_cat= $_POST['id_cat'];
$nome_categoria= $_POST['nome_categoria'];
$valor= $_POST['valor'];

$stmt = $conexao->prepare("UPDATE caixa_categoria SET nome_categoria=:nome_categoria, valor=:valor WHERE id_cat=:id_cat");

$stmt->bindparam(':id_cat', $id_cat);
$stmt->bindparam(':nome_categoria', $nome_categoria);
$stmt->bindparam(':valor', $valor);


if($stmt->execute())
{
  $res="Data Inserted Successfully:";
  echo json_encode($res);
}
else {
  $error="Not Inserted,Some Probelm occur.";
  echo json_encode($error);
}
  • You cannot repeat id’s.

  • @Sam You can explain to me better ?

  • Inside the while you are repeating several id’s, as for example the id="id_cat_update". So the JS will always get the first id you find on the page.

  • @Sam You have some example of how to do it right ?

1 answer

2


You are repeating several id’s, which is incorrect in HTML. An id serves to identify an element on the page individually, just as the CPF differentiates a citizen from another.

What you can do is remove the repeated id’s (for example, the id="id_cat_update") and take the elements by attribute name (explain further below).

But you also need to send one this for the function uptade_cat() in order to know which modal we will take the data. So put the this here:

onclick="uptade_cat(this)"

And in the role you get the this as a parameter (I used the letter m):

function uptade_cat(m) {

Ready! O m represents the button that called the function. This makes it easy to take any data inside the modal, because the button is inside the modal.

Then you will take the modal where the button is this way:

function uptade_cat(m) {
   var m = $(m).closest("div.modal");

Above I converted the m (that was the button) in the modal where the button is. So, within the function, the variable m will be the modal div.

Take the values:

Having the modal in hand (variable m), you can search within it any element using the method .find(), and you don’t need to use id’s for that (that’s why I said before to remove the repeated id’s). You can fetch an input, for example, from the attribute name:

var valor_update = m.find("[name='valor_update']").val();

Just do this with all variables within the function to get the values .val() of the elements you want.

  • TOOOP, worked perfectly. Thank you very much!!!!

  • the error and success messages no longer appear. I have to identify who is in the modal, similar to var m = $(m). Closest("div.modal"); ?

  • Yes, but switch to class: class="erro", then you think with $(m).closest("div.modal").find(".erro");

Browser other questions tagged

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