【问题标题】:Stop form post php script from opening new page阻止表单发布 php 脚本打开新页面
【发布时间】:2018-05-12 22:22:42
【问题描述】:

我有一个在多个页面上都相同的联系表单,所以我有一个 php 脚本,它被所有具有联系表单的页面调用。该脚本工作正常,处理recaptcha,发送电子邮件,一切都很好。但是,每次运行时,在通知用户邮件发送成功的警报后,它会打开一个空白页面,其中包含 php 脚本的 URL。我只想让页面保持原样 - 显示成功(或失败)警报,用户单击确定,他正盯着同一页面。表格如下:

                    <div class="col-md-7">
                        <h2>Contact Us</h2> Got a question ? Feedback? Awesome!
                        <form class="mt-4 mt-md-0" role="form" action="/php/mail.php" method="post" >
                            <div class="form-group">
                                <label for="name" class="sr-only control-label">Name</label>
                                <input class="form-control bg-faded-4" id="form_name" type="text" name="name" placeholder="Please enter your name *" required="required" data-error="Name is required.">
                                <div class="help-block with-errors"></div>
                            </div>
                            <div class="form-group">
                                <label for="email" class="sr-only control-label">Email</label>
                                <input class="form-control bg-faded-4" id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
                                <div class="help-block with-errors"></div>
                            </div>
                            <div class="form-group">
                                <label for="message" class="sr-only control-label">Message</label>
                                <textarea class="form-control bg-faded-4" id="form_message" name="message" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
                                <div class="help-block with-errors"></div>
                            </div>
                            <div class="form-group">
                            <div class="row" style="margin-bottom:30px;">
                                <span class="msg-error error"></span>
                                <div class="g-recaptcha" data-sitekey="<MY_SITE_KEY>" style="padding-left: 15px"></div>                                    
                            </div>
                            </div>
                            <button type="submit" class="btn btn-secondary btn-sm mt-2" name="submit" id="submit">Send Message</button>
                        </form>
                    </div>
                </div>

这里是 php 脚本:

<?php
  $errName = "";
  $errEmail = "";
  $errMessage = "";
  $name = $_POST['name'];
  $email = $_POST['email'];
  $message = $_POST['message'];
  $from = 'myform@mysite.com'; 
  $to = 'myemail@gmail.com'; 
  $subject = 'Message from Contact Form ';

  $body = "From: $name\n E-Mail: $email\n Message:\n $message";

// Check if name has been entered
if (!$_POST['name']) {
    $errName = 'Please enter your name';
}
else
  $sender_name = stripslashes($_POST["name"]);

// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))     {
    $errEmail = 'Please enter a valid email address';
}
else
  $sender_email = stripslashes($_POST["email"]);

//Check if message has been entered
if (!$_POST['message']) {
    $errMessage = 'Please enter your message';
}
else
  $sender_message = stripslashes($_POST["message"]);

  $response = $_POST["g-recaptcha-response"];
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = array(
        'secret' => '<MY_SECRET_KEY>',
        'response' => $_POST["g-recaptcha-response"]
    );
    $options = array(
        'http' => array (
        'method' => 'POST',
        'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $verify = file_get_contents($url, false, $context);
    $captcha_success=json_decode($verify);


   // If there are no errors, send the email
    if ($captcha_success->success==false) {
        echo "<p>You are a bot! Go away!</p>";
    } else if ( ($errName != "") ) {
      echo "<script type='text/javascript'>alert('Please enter your name.');    </script>";
    } else if ($errEmail != "") {
      echo "<script type='text/javascript'>alert('You must enter a valid email address. Please try again.');</script>";
    } else if ( $errMessage != "") {
      echo "<script type='text/javascript'>alert('You must enter some message     text. Please try again.');</script>";
    } else {


      // All the neccessary headers for the email.
      $headers = array('Content-Type: text/plain; charset="UTF-8";',
          'From: ' . $from,
          'Reply-To: ' . $from,
          'Return-Path: ' . $from,
      );

      // Send email
      $mailResponse = mail($to, $subject, $message, implode("\n", $headers));
      if ( $mailResponse == 1 ) {
        echo "<script type='text/javascript'>alert('We\'ll be in touch!');    </script>";
      } else {
        echo "<script type='text/javascript'>alert('Error sending message. Please try again.');</script>"; 
      }
    }
 ?>

我敢肯定这真的是丑陋的 php 代码,还没有真正做过太多的 php 编程。但我真正的问题是这个空白窗口在表单被 php 文件处理后出现 - 我该如何停止它?

谢谢.....

所以 php 脚本的最后一行现在是:

header('Location:http://sq36.cawgcap.org');

但这就是我所看到的。 在点击“发送”之前: 处理完表格后:

当我在警报上单击“确定”时,我会盯着一个空白页面,地址栏显示 php 脚本的位置。

【问题讨论】:

  • 您可以考虑使用 Ajax。然后,您可以在不离开页面的情况下发布表单。我还希望您在自己的文件中包含联系表格,并将其包含在您想要的所有页面中,并且没有多个副本?

标签: php html forms


【解决方案1】:

您可以使用 location.href 重定向用户。所以在警报代码之后添加:location.href="{url_of_your_form_page}";.

您应该避免使用 header 函数,因为它会向浏览器发送 http 位置标头。这将导致浏览器重定向到 url 而不会显示警报弹出窗口。

【讨论】:

  • 完美!这正是我需要知道的。谢谢你的帮助!!
【解决方案2】:

只需将用户重定向到其他页面。

使用header()函数。

脚本结束时,只需将用户重定向到其他页面,例如可能包含感谢消息的thanks.phpmail_sent_successfully.php

通过在php中使用header() function实现。

这样使用

header('Location: mail_sent.php');

所以添加这一行,用户将重定向到mail_sent.php 页面。

【讨论】:

  • 您了解@cpeddie 还是需要进一步说明?
  • 试过了,没用。查看更新的问题。
猜你喜欢
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
相关资源
最近更新 更多