I am having a problem when submitting and passing information from an HTML form into a WordPress database. I am using <form method="post">
. The form inputs are successfully inserted into the database; however, when I click refresh on the browser, the same data from the previous submission is re-inserted in the table, and is done so each time the page is refreshed. If I exit the browser, this stops the error; however, I do not want to have to close the browser each time I enter the information.
I am not sure if the problem is in the HTML, or the PHP.
I have also tried using wp_redirect($url); exit;
(redirecting to the same page), in the hopes that the redirect will clear any code that was stuck in the browser from the first submission. However, that does not fix the problem either.
Is there a way to clear the data so that when I press refresh, nothing further is submitted, until I manually fill out the form, and then re-submit?
I have tried coding wp_redirect($url); exit;
after in the HTML portion of my template page. Should I be placing this code somewhere else in the PHP file?
2
Answers
I was able to solve the problem by placing the
wp_redirect( $url); exit();
code within my theme's functions.php file.Now when I fill out the form, and click submit, the page re-loads itself. If I click refresh, the form does not reinsert the data.
Similarly to all the
headers
functions,wp_redirect
can only be used before any output of the page.See this answer for additional information.
Move
wp_redirect
before any output is done, for example where you manage yourPOST
data.Furthermore, as presented in the official documentation
wp_redirect
doesn’t exit automatically. You need to put anexit();
after it.