Jeff
Jeff

Reputation: 6110

How to avoid Page Reload Resend-Data message with PHP

I am relatively new to PHP, so my apologies if the answer is trivial. Lol

I wrote a simple Contact Us email form (actually a WordPress page-template file). All the code is in one file.

After the user submits the form and the email is sent, the file generates a Thank You message.

If the user reloads the Thank You page, they are prompted to "Resend the Form Data," which is why I am asking this question.

My question: How do I avoid the prompt to resend the form data and still keep all of my code (including the Thank You data) in one file?

EDIT: I've seen folks use headers( Location: ), but I don't think that will work for if I want to keep all my code in one file.

Upvotes: 2

Views: 7139

Answers (6)

Lukáš Neoproud
Lukáš Neoproud

Reputation: 902

This worked for me, it can be put anywhere in html file not just beginning like header() function:

<?php
if (!empty($_POST)){
?>
    <script type="text/javascript">
        window.location = window.location.href;
    </script>
<?php } ?>

I placed it into prevent_resend.php and then included it after the postdata processing was done.

// ... save data from $_POST to DB
include('prevent_resend.php');
// ... do some other stuff

Upvotes: 3

user669677
user669677

Reputation:

This worked for me:

header("Location: #");

Upvotes: 0

VoteyDisciple
VoteyDisciple

Reputation: 37803

Although I question your requirement to have all the code in one file (why couldn't you separate it, and use require_once to include shared library code?), the header('Location:') technique is still completely valid. Simply do:

header('Location: http://www.example.com/path/to/my-one-file-of-code.php?thankyou=1');

Then, in your file, you can have:

if (isset($_GET['thankyou']) && $_GET['thankyou']) {
    // Do whatever it is you do to thank the visitor.
}

Upvotes: 0

Tyler Carter
Tyler Carter

Reputation: 61557

You could redirect to a different query.

header("Location: ?page=thankyou");

Then, you don't even need to check if the POST data was sent. Just display the thank you page if page is equal to thank you.

Upvotes: 10

Ryan
Ryan

Reputation: 778

Even with a header('Location: xxx'); you can still redirect it to the same page, and either set a url parameter or a session variable to distinguish what should be shown.

Upvotes: 0

Zed
Zed

Reputation: 57648

You can use javascript to post the form and show the thank you message. This way the browser never leaves the page.

Upvotes: 0

Related Questions