phpmailer& ajax:邮件的文件附件

时间:2017-02-14 18:22:12

标签: php jquery ajax phpmailer

我有一个工作联系表单,因此用户可以通过电子邮件发送给我,而无需使用ajax刷新页面。

我希望我的用户可以选择使用他的电子邮件附加文件,但我对如何使用Ajax处理数据感到很遗憾。

以下是联系表格:

<form id="contact-form" method="post" action="/handler.php?ajax=contact">

    <input type="email" name="contact-email" id="contact-email" />

    <select name="contact-category" id="contact-category">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>

    <input type="text" name="contact-subject" id="contact-subject" />

    <textarea name="contact-message"></textarea>

    <input type="file" name="contact-attachment" id="contact-attachment" />

    <button class="btn-classic btn-orange"><i class="fa fa-paper-plane"></i> send</button>

</form>  

ajax功能:

$(function(contactSubmit) {

    var contactForm = $('#tab-contact #contact-form');
    var contactCallback = $('#tab-contact #contact-callback');

    $(contactForm).submit(function(event) {

        event.preventDefault();
        var contactData = $(contactForm).serialize();

        $.ajax({
            type: 'POST',
            url: $(contactForm).attr('action'),
            data: contactData,
        }).done(function(response) {
            $("#contact-callback").addClass("success");
        }).fail(function(data) {
            $("#contact-callback").addClass("fail");
        });

    });


});  

和2个php函数来验证数据并发送邮件:

<?php

public static function contact() {

    $mail_from_email = filter_var(trim($_POST['contact-email']), FILTER_SANITIZE_EMAIL);
    $mail_from_name = 'User1';
    $mail_to_email = 'webmaster@site.com';
    $mail_to_name = 'Webmaster';
    $mail_subject = '['.$_POST['contact-category'].'] '.trim($_POST['contact-subject']);
    $mail_body = trim($_POST['contact-message']);
    $mail_attachment = $_FILES['contact-attachment'];

    $sendMail = action::sendMail($mail_from_email, $mail_from_name, $mail_to_email, $mail_to_name, $mail_subject, $mail_body, $mail_attachment);

}

public static function sendMail($mail_from_email, $mail_from_name, $mail_to_email, $mail_to_name, $mail_subject, $mail_body, $mail_attachment) {

    require $_SERVER['DOCUMENT_ROOT'].'/phpmailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;

    //$mail->SMTPDebug = 3;                                 // Enable verbose debug output

    $mail->isSMTP();                                        // Set mailer to use SMTP
    $mail->Host = config::get('mail_smtp_host');            // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                                 // Enable SMTP authentication
    $mail->Username = config::get('mail_smtp_username');    // SMTP username
    $mail->Password = config::get('mail_smtp_password');    // SMTP password
    $mail->SMTPSecure = config::get('mail_smtp_security');  // Enable TLS encryption, `ssl` also accepted
    $mail->Port = config::get('mail_smtp_port');            // TCP port to connect to

    $mail->setFrom($mail_to_email, $mail_from_name);
    $mail->addAddress($mail_to_email, $mail_to_name);       // Add a recipient
    $mail->addAddress('');                                  // Name is optional
    $mail->addReplyTo($mail_from_email, $mail_from_name);
    $mail->addCC('');
    $mail->addBCC('');

    $mail->addAttachment($mail_attachment);                 // Add attachments
    $mail->addAttachment('');                               // Optional name
    $mail->isHTML(true);                                    // Set email format to HTML

    $mail->Subject = $mail_subject;
    $mail->Body    = $mail_body;
    $mail->AltBody = '';

    if(!$mail->send()) {
        return $mail->ErrorInfo;
    } else {
        return true;
    }

}

?>  

但是我一直困在第1步:我的php函数无法从文件输入中检索数据,似乎ajax没有发送有关此输入字段的信息。
Php返回Undefined index: contact-attachment

任何人都可以指导/帮助我完成这项工作吗?我目前的代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

您的表单标记不包含所有属性。

替换

<form id="contact-form" method="post" action="/handler.php?ajax=contact">

<form id="contact-form" method="post" action="/handler.php?ajax=contact" accept-charset="utf-8" enctype="multipart/form-data">

$(document).ready(function() {
$('#contact-form').submit( function( e ) {
var formData = new FormData($(this)[0]);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
    return false; 
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact-form" method="post" action="/handler.php?ajax=contact" accept-charset="utf-8" enctype="multipart/form-data">

    <input type="email" name="contact-email" id="contact-email" />

    <select name="contact-category" id="contact-category">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>

    <input type="text" name="contact-subject" id="contact-subject" />

    <textarea name="contact-message"></textarea>

    <input type="file" name="contact-attachment" id="contact-attachment" />

    <button class="btn-classic btn-orange"><i class="fa fa-paper-plane"></i> send</button>

</form>