How to change status with AJAX?

Asked

Viewed 479 times

1

I have a system where the administrator can approve or disapprove the user, It is all ready, but I want to know how to do this process with ajax, so that every time I approve or disapprove a user the page does not give refresh.

Approval page

    <div class="row">
         <div class="col-md-5"><h3>Autorização de Usuarios</h3></div>
         </div>
  <div class="row alinha-tabela">
    <div class="row">
    <div class="col-md-6">
      <div class="table-responsive shadow-z-1">
        <table class="table table-striped table-condensed table-hover">
         <thead>
           <tr>
             <th>Codigo</th>
             <th>Usuario</th>
             <th>Status</th>
           </tr>
         </thead>
            <tbody>
              <?php  
                //Consulta
                $buscarusuario=$pdo->prepare("SELECT * FROM usuario");
                $buscarusuario->execute();

                //atribuindo dados á variavel
                $linha = $buscarusuario->fetchAll(PDO::FETCH_ASSOC);

                //percorrendo a variavel para listar os dados
                foreach ($linha as $listar) {
                    $iduser = $listar['id'];
                    echo "<tr>";
                    echo " <td>".$listar['id']."</td>";
                    echo "<td>".$listar['nome']."</td>";
                    if($listar['status'] > 0 ){
                    echo "<td class='success text-success'>Aprovado 
  <form method='post' action='pg/mudastatus.php' id='f-desaprova' class='form-muda'>
      <button type='submit' class='btn btn-xs btn-success alinha-btn' name='desaprova' value='$iduser'>Desaprovar</button>
</form>
                    </td>";
                  }else{
                    echo "<td class='danger text-danger'> Aguardando aprovação 
  <form method='post' action='pg/mudastatus.php' id='f-aprova' class='form-muda'>
   <button type='submit' class='btn btn-xs btn-danger alinha-btn' name='aprova' value='$iduser' >Aprovar</button>
</form>

                    </td>";
                  } 
  }
              ?>
            </tbody>
        </table>
      </div>
    </div>

mudastatus.php

    <?php
 include '../config/config.inc.php'; 


if(isset($_POST['aprova'])){

   $atualizarstatus = $pdo->prepare("UPDATE usuario SET status=1 WHERE id=:ID ");
   $atualizarstatus->bindValue(":ID",$_POST["aprova"]);
   $atualizarstatus->execute();
   $linha = $atualizarstatus->rowCount();

   if($linha > 0){
     header("location:../logado.php");
   }else{
    echo "Erro ao Mudar status";
   }
}elseif (isset($_POST['desaprova'])){

   $atualizarstatus = $pdo->prepare("UPDATE usuario SET status=0 WHERE id=:ID ");
   $atualizarstatus->bindValue(":ID",$_POST["desaprova"]);
   $atualizarstatus->execute();
   $linha = $atualizarstatus->rowCount();

   if($linha > 0){
     header("location:../logado.php");
   }else{
    echo "Erro ao Mudar status";
    header("location:../logado.php");
   }
}

2 answers

0

If you are going to use jQuery, you do it the following way:

$.ajax({
    type: 'POST',
    data: {
        aprova: true,
    },
    url: 'mudastatus.php',
    success: function(data){
       alert('ok');
    }

});

But there are some other things you need to fix in your code.

  1. No need to use the header method, since you will not redirect to anywhere ajax.
  2. You don’t need to put two parameters in $_POST, one approves and the other disapproves, you can put only one, for example status, if status is approved, executes such action, if disapproved executes another action. Cleaner, right?
  • hello friend could explain me more detailed how would be my code with ajax and let cleaner without two form ?

0

I won’t be able to help with the PHP, but I’ll try to give an orientation when the request AJAX.

first, try to put all the inputs that you plan to receive on the server within a form

let’s take as an example the following mark-up html.:

<form id="formulario" action="atualiza.php" method="POST">
  <div>
    <label>
      Autor:
      <input id="Author" name="Author" type="text" />
    </label>
  </div>
  <div>
    <label>
      Data Referencia:
      <input id="DataReferencia" name="DataReferencia" type="text" />
    </label>
  </div>
  <div>
      <label>
      Registos 01:
      <input id="Registos_1" name="Registos[]" type="text" />
    </label>
  </div>
  <div>
      <label>
      Registos 02:
      <input id="Registos_2" name="Registos[]" type="text" />
    </label>
  </div>
  <div>
      <label>
      Registos 03:
      <input id="Registos_3" name="Registos[]" type="text" />
    </label>
  </div>
  <div>
    <input id="Enviar" type="submit" value="Value" />
  </div>
</form>

I believe you are familiar with the code above, and know how to recover the fields Autor, DataReferencia and Registos[] when they arrive at your server.

The way you will recover the data on the server will not change, what will change is how to send the data and recover the same.

for this, I advise you to manipulate the event submit of form#formulario

var formulario = document.getElementById("formulario");
formulario.addEventListener("submit", function (event) {
  // cancelando o envio sincrono do formulario.
  event.preventDefault();

  var data = new FormData(formulario);
  var httpRequest = new XMLHttpRequest(formulario.method, formulario.action, true);
  httpRequest.open();
  httpRequest.addEventListener("readystatechange", function (event) {
    if (httpRequest.readyState == 4) {
      if (httpRequest.status == 200) {
        // a requisição ajax deu certo
        console.log(httpRequest.response);
      } else {
        // ocorreu um erro durante a requisição AJAX.
        console.error(httpRequest.statusText);
      }
    }
  });
  httpRequest.send(data);
});

in your code PHP you have two options, returns a string with a HTML already assembled and replace the HTML page, or return an object JSON and use it to manipulate your page.

In both cases, you will need to set a property responseType of your httpRequest and manipulate the return as follows:

Text/HTML

// antes de enviar
httpRequest.responseType = "text";

// ao receber a resposta com sucesso.:
// limpando o DOM que vai receber o novo conteudo.
var destino = document.getElementById("destino");
while (destino.firstChild) {
  destino.removeChild(destino.firstChild);
}  

// montando o novo conteudo.
var parser = new DOMParser();
var node = parser.parseFromString(xmlHttp.responseText, "text/html");
destino.appendChild(node.documentElement);

JSON

// antes de enviar
httpRequest.responseType = "json";

// ao receber a resposta com sucesso.:
// digamos que você passou o seguinte json.:
// { novoValor: 'Hello World' }.
var destino = document.getElementById("destino");
var campo = destino.querySelector("#id_campo");
campo.value = xmlHttp.response.novoValor;

as to return a JSON in PHP, you can convert your object as follows:

echo json_encode($meu_objeto);

Browser other questions tagged

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