How to change the image when changing the status in the Mysql database without refresh with jquery

0

I have the following listing:

HowwouldIdothatbyclickingtheexclamationicon,changetothecheckiconandviceversaandalsochangethestatusinthedatabase?ThePHP/MysqlcodeIknowhowtodo,butthejquerythatdoesnotbagmuch.SincethestatusiscomingfromtheDB,thecodelookslikethis:

$sql=mysqli_query($this->conexao,"SELECT * FROM documentos");

while($peListar = mysqli_fetch_object($sql)){    

$statusDoc = ($peListar->StatusDocumentos == "A")?"<span style='color: red'><i class=\"fas fa-exclamation-circle fa-lg\" id=\"inativo\"></i></span>":"<span style='color: green'><i class=\"fas fa-check-circle fa-lg\" id=\"ativo\"></i></span>";
    echo $statusDoc;

}
    
asked by anonymous 24.10.2018 / 22:58

2 answers

0

I was able to do it, but I do not know if it is correct and feel free to correct me;)

Listing coming from PHP

<?php
...
$sql = mysqli_query($conexao,"SELECT * FROM pe_documentos_pendentes");
while($peListar = mysqli_fetch_object($sql)){
      $statusDoc = ($peListar->StatusDocumentos == "A")?"<a href='#!' class='alterar' data-id='".$peListar->IdDocumentos."' data-status='E' style='color: red'><i class=\"fas fa-exclamation-circle fa-lg\" id=\"inativo\"></i></span>":"<a href='#!' class='alterar' data-id='".$peListar->IdDocumentos."' data-status='A' style='color: green'><i class=\"fas fa-check-circle fa-lg\" id=\"ativo\"></i></a>";
      echo $statusDoc."<br>";
 }
...
?>

In Jquery, I did it this way:

<script>
  $(document).ready(function(){
    $(".alterar").click(function(){
      var posts = $(this).attr('data-id');
      var status = $(this).attr('data-status');
      $.post('alterar.php', {key: posts, status: status}, function(retorno){
             window.location.reload(true);
       });
    });
  });
</script>

On the alter.php page:

mysqli_query($conexao,"UPDATE pe_documentos_pendentes SET StatusDocumentos = '".$_POST["status"]."' WHERE IdDocumentos = '".$_POST["key"]."';");
    
25.10.2018 / 02:45
0

The way you did is almost there, but you're still reloading the page with window.location.reload . In your PHP file you can make the logic return the current status, just like it did in the listing, something like:

$query = mysqli_query($conexao,"UPDATE pe_documentos_pendentes SET StatusDocumentos = '".$_POST["status"]."' WHERE IdDocumentos = '".$_POST["key"]."';");
$count = mysql_num_rows($query);

if($count >= 1) {
 $response['success'] = true;
 echo json_encode($response);
}

And in Jquery

$.post('alterar.php', {key: posts, status: status}, function(retorno){
  //você possui o retorno da sua página alterar.php aqui, 
  data = $.parseJSON(retorno);
  alert(data.response);    
  //o que precisa fazer é apenas manipular essa resposta, 
  //criar seu ícone, substituir o atual no DOM, e fazer com que esse novo
  //ícone passe por esse mesmo evento de post
});
    
25.10.2018 / 22:12