【问题标题】:How to send confirmation email via PHP and Ajax?如何通过 PHP 和 Ajax 发送确认邮件?
【发布时间】:2016-01-15 00:29:30
【问题描述】:

我正在开发一个带有 Ajax 的简单 PHP 表单的项目。表单成功发送电子邮件,但在 AJAX 消息中显示我设置的错误消息:'Oops! An error occured and your message could not be sent。 ' 会不会是服务器问题?

我还想在用户在我的网站上提交表单后向他们发送一封感谢(表单提交确认)电子邮件。

HTML 代码:

  <form id="ajax-contact" method="post" action="mailer.php">
      <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" placeholder="Name" required name="name">
      </div>
      <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" id="email" placeholder="email" name="email" required>
      </div>
      <div class="form-group">
        <label for="message">Message:</label>
        <textarea class="form-control" rows="3" id="message" name="message"></textarea>
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>

PHP mailer.php 代码:

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "receiveremail@somewhere.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

AJAX 代码:

$(function() {
    // Get the form.
    var form = $('#ajax-contact');

// Get the messages div.
var formMessages = $('#form-messages');

// Set up an event listener for the contact form.
$(form).submit(function(event) {
    // Stop the browser from submitting the form.
    event.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();
    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })

    .done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');

// Set the message text.
$(formMessages).text(response);

// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})

.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');

// Set the message text.
if (data.responseText !== '') {
    $(formMessages).text(data.responseText);
} else {
    $(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
      });
});

【问题讨论】:

  • 先运行没有ajax的邮件文件,看看有没有报错。
  • 我在删除它工作的 ajax 后运行该文件,我没有收到任何错误,但浏览器重定向到 mailer.php 并且它是空白页面。
  • mailer.php 中添加error_reporting(E_ALL) 并检查您遇到的错误。
  • 未收到任何错误并提交表单
  • 是的,我收到了电子邮件

标签: php ajax forms email


【解决方案1】:

只需更改此行并检查一次。即使我有同样的问题,我也是这样解决的,

data: formData

data: {"postvalues":formData},

data: formData to data: {name: "sample",email:"your emal",message:"hi how are you"}

如果您使用的是第一个,请在 mailer.php 中进行必要的更改。像这样

$post = $_POST['postvalues'];
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];

如果你按照第二种方法,你不能serialize()表单,并且不需要更改mailer.php中的任何内容。

要向填写表单的用户发送电子邮件,请使用此

if (mail($recipient, $subject, $email_content, $email_headers)) {
    // Set a 200 (okay) response code.
    http_response_code(200);
    echo "Thank You! Your message has been sent.";
    mail($email, "Contact Us", "Thank you for contacting us, we will get back to you soon", $email_headers)
}

【讨论】:

  • 如何向提交表单的用户发送感谢邮件?
  • 使用您的文件mailer.php,添加代码发送给填写表格的用户。
  • 尝试了第一个选项仍然是相同的结果,在表单消息上它给出了一个错误但电子邮件处理成功
  • 如果您提供所需的代码会有帮助
  • 用第二种方法试一次。
猜你喜欢
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 2015-10-24
  • 2016-09-30
相关资源
最近更新 更多