Redirect After Form Processing

Raven

Redirect After Form Processing

After processing an html form, it is often a good idea to redirect the user to a new url, rather than just presenting the results. Consider this php example:

if ($_POST["name"]) {
  # do something
  print "Thanks for posting " . $_POST["name"] . "<br>";
}

After processing the form input, it prints a message. This works fine until the user reloads the page for some reason. They may click refresh, or more likely they will click away and then back to this page. That’s when they get this message:

Confirm
The page you are trying to view contains POSTDATA. If you resend the data, any action the form carried out (such as a search or online purchase) will be repeated. To resend the data, click OK. Otherwise, click Cancel.

If they click Cancel, they get nothing. If they click OK, their form input gets resubmitted, and the code above gets run a second time. It’s possible that the code could be smart enough to ignore duplicate posts, but we really need to get rid of the warning message and prevent unnecessary confusion.

Let’s change our example to work like this:

if ($_POST["name"]) {
  # do something
  header("Location: thanks.html");
  exit;
}

Now that we’ve sent them to a new page, they can click the Back button and get back to the original form. They won’t get the warning, and there’s no danger of them accidentally resubmitting the same information.

I usually do my form processing at the beginning of the same php page that displays the form. After the form processing is complete, I redirect them back to PHP_SELF where they can see the results of their submission.

Error processing gets a little trickier using this method. One option is to do as much form validation as you can in javascript. It’s faster and easier for the user, and eliminates some mess on the backend. Another thing you can do is create error codes for different conditions. Here’s an example:

if ($_POST["name"]) {
  $url = $_SERVER["PHP_SELF"];
  if ($_POST["name"] == "scott") {
    $url .= "?error=1";
  } else {
    # do something
  }
  header("Location: $url");
  exit;
}
$error_msg = "";
if ($_GET["error"] == 1) {
  $error_msg = "That name is reserved.  Please choose another.";
}

For forms using the GET method, the warning message is not an issue, but resubmission is even more likely. Once a GET form is submitted, the url the browser sees contains all the form variables. If you don’t redirect them away from this url immediately, they could bookmark or email this url. Next time they visit the bookmark, all those variables will be submitted, causing unwanted or unexpected behavior.

Comments are closed on this post