PHP表单提交然后检查网址以显示相应的内容

时间:2015-11-04 22:54:29

标签: javascript php jquery html ajax

我正在尝试创建一个表单来注册电子邮件订阅,这些订阅会发送到确切的目标(我们的邮件服务)。最初希望表单使用ajax jquery并在提交时将表单更改为成功消息或错误(取决于结果)。据悉,ajax表单提交不能在原始域SOURCE

之外完成

问题:

尝试让此表单提交并将数据附加到主页网址,以便在加载时显示不同的内容。有三种状态

  1. 如果GET为空,则加载表单
  2. 如果GET注册=错误
  3. ,则加载错误消息和表单
  4. 如果GET注册=成功
  5. ,则加载成功消息

    <?php
    if (empty($_GET)) {
    echo'
    <form action="emailhost.net/subscribe.aspx" name="subscribeForm" method="post" class="forms" id="form">
    <input type="hidden" name="thx" value="example.com/?signup=success" />
    <input type="hidden" name="err" value="example.com/?signup=error" />
    <input type="text" name="Full Name" placeholder="Name" />
    <input type="text" name="Email Address" placeholder="Email Address" />
    <input type="submit" />
    </form>'
    ;}
    
    if(isset($_GET["signup"]) && trim($_GET["signup"]) == "error"){
    echo '
    <p>There was an error. Please try again</p>
    <form action="emailhost.net/subscribe.aspx" name="subscribeForm" method="post" class="forms" id="form">
    <input type="hidden" name="thx" value="example.com/?signup=success" />
    <input type="hidden" name="err" value="example.com/?signup=error" />
    <input type="text" name="Full Name" placeholder="Name" />
    <input type="text" name="Email Address" placeholder="Email Address" />
    <input type="submit" />
    </form>'
    ;}
    
    if(isset($_GET["signup"]) && trim($_GET["signup"]) == 'success'){
    echo'
    <p>Thank you for signing up!</p>'
    ;}?>

    隐藏的输入被发送到我们的电子邮件主机,并根据错误或成功,主机选择正确的值发回。

    目前这不起作用。我从here

    获得了php代码

1 个答案:

答案 0 :(得分:0)

执行此操作的正确方法是将PHP用作您与客户端之间的一种代理(您从客户端收集表单数据,代表他们将其提交给第三方服务器,并检索结果)。

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postdata = http_build_query(
                    $_POST, /* or wherever else you collected the data from */
                );
    $opts = [
      'http'=> [
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata,
      ]
    ];

    $context = stream_context_create($opts);

    $result = file_get_contents('http://emailhost.net/subscribe.aspx', false, $context);
    if ($result) {
        echo "<h1>Success!</h1>";
    } else {
        echo "<h1>ohnoes...</h1>";
    }
} else {
?>
<form action="myscript.php" name="subscribeForm" method="post" class="forms" id="form">
<input type="hidden" name="thx" value="example.com/?signup=success" />
<input type="hidden" name="err" value="example.com/?signup=error" />
<input type="text" name="Full Name" placeholder="Name" />
<input type="text" name="Email Address" placeholder="Email Address" />
<input type="submit" />
</form>
<?php
}