【问题标题】:Php - Mail subscribe FormPhp - 邮件订阅表格
【发布时间】:2014-08-10 14:26:21
【问题描述】:

我有 2 个文件:

  1. Index.html
  2. sendmail.php

代码运行良好,但我试图在同一页面上回显消息,而不是翻转到另一个页面或自动重定向到 index.html。

我尝试了很多选项,但都没有成功。我需要一些帮助 - 我是 php 新手。

代码如下:

索引.html:

<form class="form-inline" action="php/sendmail.php" method="post">
<input type="text" name="email" placeholder="Please enter your email...">
<button type="submit" class="btn_email">Subscribe</button>
</form>'

sendmail.php:

<?php
$to = "info@mywebsite.com"; // my email address 
$from = "no-reply@mywebsite.com"; // from (my email)

$headers = "From: " . $from . "\r\n";

$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];


if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{ 
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
$filename=$_SERVER["PHP_SELF"];
    echo 'Your e-mail (' . $_POST['email'] . ') has been added to our mailing list!';
}
else
{
   echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';   
}
} 
else
{
   echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';   
}

【问题讨论】:

  • “我正在尝试在同一页面上回显消息” - 不是 .html 文件扩展名,除非你指示 Apache将.html 文件视为 PHP。

标签: php html forms email


【解决方案1】:

为此,您需要使用 AJAX。 AJAX 允许在页面重新加载或重定向时执行服务器端代码。

最简单的方法是使用 JQUERY。

$('form').submit(function(e) {

   e.preventDefault();

var email = $('input[type="email"]').val();

var queryString = "email="+email;

$.ajax({

    url : "php/sendmail.php",
    type : "POST",
    data : queryString,
    dataType : "html",
    success : function(output) {

        $('body').append("<p>"+output+"</p>");

    }

});

});

您还应该将 index.html 保存为 index.php。

还要确保在页面上包含 JQUERY。您可以通过在 index.php 中的任何位置放置:&lt;script src="http://code.jquery.com/jquery-1.9.1.min.js"&gt;&lt;/script&gt; 来做到这一点

【讨论】:

  • 您好,谢谢您的回复。 .但是,我是否应该将此脚本与我以前的 php 代码一起添加。 .因为试图执行它..没有任何反应。
  • 我已将索引文件重新保存为 php 。 .
  • 我忘了防止表单提交的默认设置。这将停止表单提交,就像通常单击提交按钮一样。也可能你没有包括JQUERY?我刚刚用你的表单测试了上面的代码,它工作正常:)
【解决方案2】:
// display form if user has not clicked submit
<?php
if (!isset($_POST["submit"])) {
?>

<form class="form-inline" action="php/sendmail.php" method="post">
    <input type="text" name="email" placeholder="Please enter your email...">
    <button type="submit" class="btn_email">Subscribe</button>
</form>`

<?php 
}


else { 
// the user has submitted the form
//enter your php code here 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2020-03-18
    • 1970-01-01
    • 2017-03-12
    • 2014-02-13
    • 2022-10-24
    • 1970-01-01
    相关资源
    最近更新 更多