PHP表单提交和重定向

PHP form submit and redirect

本文关键字:重定向 表单提交 PHP      更新时间:2023-09-26

所以我有一个模式表单,我想在其中获取输入的字段,并将其发送到我想要的电子邮件地址,然后将其重定向到某个网页/下载页面我已经用PHP完成了这项工作,但我想使用客户端重定向它,只需使用PHP邮件进行字段解析即可获得电子邮件,我必须创建大量的PHP表单才能做到这一点,因为重定向url在许多情况下是不同的。

这是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");
} 

现在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>

您可以使用JavaScript的window.location.assign()函数重定向到另一个页面。请尝试以下操作。

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

您可以将这段代码放在form2.php文件中。

请记住,您需要form2.php文件中的HTML代码才能正常工作
请确保将其放置在head标签下方。

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

如果要延迟重定向(以秒为单位),请更改content属性的

为什么不通过ajax提交表单,并在成功响应时重定向表单呢。

<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>