简体   繁体   中英

PHP form submit and redirect

So I have a modal form where I want to get the inputted fields and send it to my desired email address and then redirect it to a certain webpage/download page I have managed to do it with PHP however I want to redirect it using client side and just use PHP mail for the field parsing to get the email and I have to create tons of PHP forms just to do so because the redirect url is different on many cases.

Here is the PHP

$to = "some@email.com";
$subject = "Contact Page";
$headers = "From: Contact Page";
$forward = 1;
$location = "somelocation";
$date = date ("l, F jS, Y");
$time = date ("h:i A");

$msg = "Below is the result of your feedback form. It was submitted on $date at $time.\n\n";

if ($_SERVER['REQUEST_METHOD'] == "POST") {
        foreach ($_POST as $key => $value) {
                $msg .= ucfirst ($key) ." : ". $value . "\n";
        }
}
else {
        foreach ($_GET as $key => $value) {
                $msg .= ucfirst ($key) ." : ". $value . "\n";
        }
}
mail($to, $subject, $msg, $headers);
if ($forward == 1) {
    print("You will be redirected to your download link shortly";) 
    header ("Location:$location");
}
else {
    include("index.html");
} 

now the html

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">x</span>
    <form method="POST" onsubmit="myFunction()" action="form2.php"> 

<label for='name'>Name: </label>
<input type="text" name="name" >
<label for='email'>Email: </label>
<input type="text" name="email" >
<input type="submit" id="submit" value="Submit" name="submit">
<script>
function myFunction() { 
alert("form Submitted Successfully you will be redirected shortly");
        }
</script>

You can use JavaScript's window.location.assign() function to redirect to another page. Try the following.

<script>
   function myFunction() { 
     alert("form Submitted Successfully you will be redirected shortly");
     window.location.assign("http://urlOfThePageYouWantToRedirectTo");
   }
</script>

You can place this piece of code in your form2.php file.

Keep in mind that you need HTML code inside your form2.php file for this to work.
Make sure you place it under head tag.

<meta http-equiv="refresh" content="0; url=http://YourRedirectLink.com/" />

Change the value of content attribute if you want to delay the redirect (in seconds).

Why don't you submit your form via ajax and redirect it on successful response.

<script>
function myFunction() {
//ajax code
//on success 

   alert("form Submitted Successfully you will be redirected shortly");
   //Redirect on url you want
   window.location.href= "write_your_url_here";

}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM