在提交时动态地将表单替换为消息

时间:2015-08-23 23:15:55

标签: php html forms

我已经编写了一个基本的PHP脚本,用于在我的联系表单提交时生成电子邮件,但就目前而言,它会将用户重定向到错误或谢谢页面,这有点笨拙。我想用错误或成功消息动态替换整个表单(或者至少是提交按钮)。这里的问题是我的PHP知识有限。

HTML:

<form role="form" method="post" action="contact-form.php">
    <input type="text" class="input-field" name="name" id="name" placeholder="Name" required data-errormessage-value-missing="Hey, I need your name!" />
    <input type="email" class="input-field" name="email" id="email" placeholder="Email" required data-errormessage-value-missing="Don't forget your email address!" />
    <textarea name="message" class="textarea-field" id="message" placeholder="Message" required data-errormessage-value-missing="Please enter your message."></textarea>
    <div class="g-recaptcha" data-sitekey="6LeJpAsTAAAAALzJoRZzq4_fovbjjSG2iaxvVHzy"></div>
    <input type="submit" value="Contact Me" class="btn btn-primary btn-xl" />             
</form>

PHP:

<?php

// Load reCAPTCHA library
include_once ("autoload.php");

$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$emailFrom = $email;
$emailTo = "my@email.com";
$subject = "Contact Request";

// Prepare email body text
$body = "<strong>Name:</strong> $name <br /> <strong>Email:</strong> $email <br /> <strong>Message:</strong> $message";

$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $name <$emailFrom>" . "\r\n";

$secret = 'XXX';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()){
    $success = mail($emailTo,$subject,$body,$headers);
    header("Location: " . "http://" . $_SERVER['HTTP_HOST'] . '/thankyou.html');
}else{
    header("Location: " . "http://" . $_SERVER['HTTP_HOST'] . '/error.html');
}

?>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

使用以下内容:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo 'Your message goes here.';
}
else
{
?>

    <!-- Your form HTML goes here. -->

<?php
}
编辑:抱歉,我对你的HTML没有仔细观察。请尝试以下方法。将您拥有的所有现有PHP代码放入contact-form.php文件中。把你的html表单放在index.php中。在PHP代码中,删除header语句并将其替换为echo语句 - 无论您想要放在那里的任何消息。