How to change status with AJAX?

1

I have a system where the administrator can approve or disapprove the user, everything is 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");
   }
}
    
asked by anonymous 05.07.2016 / 01:08

2 answers

0

I will not be able to help with the PHP part, but I will try to give an orientation when the AJAX request.

First, try putting all the inputs that you plan to receive on the server within 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 think you're familiar with the code above, and you know how to retrieve the Autor , DataReferencia , and Registos[] fields when they reach 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 retrieve 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, return a string with a HTML already mounted and replace the HTML of the page, or return a JSON object and use it to manipulate your page .

In both cases, you will need to set a responseType property of your httpRequest and handle 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 for returning a JSON in PHP, you can convert your object as follows:

echo json_encode($meu_objeto);
    
05.07.2016 / 15:10
0

If you are going to use jQuery, you do it as follows:

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

});

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

  • You do not need to use the header method, since you will not redirect ajax to anywhere.
  • You do not need to put two parameters in $ _POST, one approves and another disapproves, you can put only one, for example status , if status is approved, performs such action, if it is disapproved execute another action. Cleaner, right?
  • 06.07.2016 / 11:35