Reputation: 6193
Is there anyway to redirect the user after posting a HTML form?
I have a form which looks like this
<form action="/URL/" method="post">
<input type="radio" name="answer" value="W" />W<br />
<input type="radio" name="answer" value="X" />X<br />
<input type="radio" name="answer" value="Y" />Y<br />
<input type="radio" name="answer" value="Z" />Z<br />
<input type="submit" />
</form>
Is there anyway I can redirect the user to a new page after they click the submit button? I found a bit of javascript however that seemed to stop the post from working :S
Cheers!
Upvotes: 0
Views: 10422
Reputation: 174947
Yes, use a redirect header:
header("Location: http://new.location.com/w00t");
This must be called before any output is sent.
Take note that everything after the header call would still be executed! So you'll need die()
or exit()
afterwards to prevent unexpected results.
Upvotes: 2
Reputation: 1258
You can just simply specify URL to which form will go after being submitted.
<form action="http://localhost/redirected.php" method="post">
You can check with PHP whether form is submitted and then redirect:
if (isset($_POST['answer']))
header('Location: redirect.php');
And You can achieve this with javascript/jquery.
$('#submit_button').click(function () {
// do everything with variables
window.location = 'redirect.php';
});
Upvotes: 1
Reputation: 59699
If you're using PHP, do it on the server:
if( isset( $_POST['answer'])) {
header( 'Location: http://www.example.com/newurl');
exit();
}
Note that you should be using a full URL in the header()
call, and that you likely want to exit()
after calling header()
in this case.
Upvotes: 6
Reputation: 16951
Yep, just post the data using ajax and then use window.location = 'http://xxxx.com'
to redirect user to location of your choice.
That's assuming you want to redirect user without using server-side location headers (like the other ones posted).
Upvotes: 0
Reputation: 33502
You can use a simple php header('yourlocation.php');
to move them away from the form.
The PHP that your form action pointed to will still continue executing even if your header() is at the top of the php file.
The header redirect will take care of the user hitting refresh - it has already moved them past the point of sending form data, so even if they refresh, it will just open the page again sans any form submissions.
An example is as fololows:
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
// Process Form Data, insert to database, whatever you want... then
header('Location: http://www.example.com/');
?>
The user then ends up at wwww.example.com and they can spam refresh as much as they like, but all the processing has already taken place. It won't resend the information (or process their payment again or anything else).
Upvotes: 2