Clear form data if there is "refresh" of the page?

Asked

Viewed 1,809 times

1

I am performing a simple test and would like to know if there is how to clear the form data if the user gives a refresh in the browser.

<?php
$test1 = "";
$test2 = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{   $test1 = $_POST['test1'];
    $test2 = $_POST['test2'];
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
    <input type="text" name="test1" value="<?php echo $test1;?>"/>
    <input type="text" name="test2" value="<?php echo $test2;?>"/>
    <input type="submit" name="btn_sub" value="Enviar" />
</form>

Every time I type something in the fields if I give it refresh in the browser the data remains. I wonder if it is possible to clear these fields by clicking on the refresh of the browser.

  • Idea: With onload javascript setar values and innerHtml form elements as empty. Note that for each type of element you will need a different treatment.

  • I would like to see with php, but vlw the tip

  • I don’t know how to do it in php, but you can see if there is a function to clear the cookie and the cash of the page when there is refresh.

  • I’m a little confused. The data is filled with data from POST, So you’re basically putting them there. Then, when the user refreshes the page, the browser sends that alert to resend the data and these appear again on the page. If I understand correctly, what you would like is for refresh not to resend the form data or for that data to be ignored the second time you open the page, is this?

  • If my above assumption is true, what you can do is save a flag in the user session the first time it shows the form. The second time, if the flag is present, you do not put the values in the fields.

1 answer

3


Change the request headers with header and tell the browser to save nothing in cache:

<?php
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$test1 = "";
$test2 = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $test1 = $_POST['test1'];
    $test2 = $_POST['test2'];
}?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
    <input type="text" name="test1" value="<?php echo $test1;?>"/>
    <input type="text" name="test2" value="<?php echo $test2;?>"/>
    <input type="submit" name="btn_sub" value="Enviar" />
</form>

Source: How to control web page caching, Across all browsers?.

Browser other questions tagged

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