How to clear input fields after Ubmit?

Asked

Viewed 2,552 times

0

It is as follows: when you submit the form, in the [POST] method, the variables will be incapsulated in the URL bar. In the [GET] method, the variables are exposed in the URL bar. However, when updating the page in the [POST] method, variables are stored and resends the form. How to solve?

3 answers

1

I saw you put in tags jQuery, then you can use it, so you will not have problems, a simple use example is.

// PHP
$retorno = array();
$sql = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$sql->execute(array($_POST['id'])); 

$retorno['dados'] = $sql->fetchAll();

die(json_encode($retorno))

With this, your PHP will already return one json for your ajax that will stay that way...

function listarUsuarios(){
   $.ajax({
      type: 'POST',
      url: 'SUA URL DO ARQUIVO PHP',
      dataType: 'json',
      data: {
         id: 1
      },
      success: function(data){
          console.log(data)
          $('body').append('<h1>'data.nome'</h1>')
      }
   })
}

// Aqui você executa sua função
listarUsuarios()

And that way you solve your problem.

0

Anyway how it resolves?

Just create this Function, :

// Limpar URL
function removeURL($url, $titulo){
  echo 'window.history.pushState("'.$url.'", "'.$titulo.'", "'.$url.'");
}

Right after you create the following code:

//Limpar METHOD POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
 removeURL($_SERVER['HTTP_REFERER'], 'Aqui você digita o Titulo da Página');
}
  • 2

    Please explain your solution better.

0

A solution would be as I put in the diagram below: receive the form via POST, do what should be done, create a SESSION as a result of the process and then make a redirection to the page itself. This way, if F5 key is pressed, there will be no new data Ubmit:

The scheme would look like this (it’s just a schematic concept):

<html>
<body>

<?php
// SE EXISTE POST E A SESSION ESTÁ VAZIA, ENTRA NESTE IF
if (isset($_POST) && SESSION == ""){
   // 1. recebo os dados do formulário
   // 2. faço o que tem que fazer com os dados
   // 3. crio uma SESSION com "ok" ou "erro"
   // 4. faço um redirecionamento para a própria página
         Header("Location: pagina.php");
}
?>

<?php
// SESSION CHEIA

// Mostro a mensagem de acordo com o valor da SESSION:

if (SESSION == "ok"){
    echo 'Dados cadastrados com sucesso';
}else if (SESSION == "erro"){
    echo 'Houve um erro';
}

Apago a SESSION;
?>

</body>
</html>

Browser other questions tagged

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