Php - Mail订阅表格

时间:2014-06-19 22:01:32

标签: php html html5 forms email

我有2个文件:

  1. 的index.html
  2. sendmail.php
  3. 代码工作正常,但我尝试在同一页面上回显邮件而不会翻转到另一个或自动重定向到index.html。

    我尝试了许多选项而没有成功。我需要一些帮助 - 我是php的新手。

    以下是代码:

    的index.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'] . ')';   
    }
    

2 个答案:

答案 0 :(得分:0)

要执行此操作,您需要使用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

中的任何位置放置:<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>来完成此操作

答案 1 :(得分:0)

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