duanjia1870 2017-02-14 18:22 采纳率: 0%
浏览 118
已采纳

phpmailer&ajax:邮件附件

I have a working contact form so a user can email me while not having to refresh the page, using ajax.

I'd like my user to have the option to attach a file with his email, but I'm kind of lost as how to process the data with Ajax.

Here is the contact form :

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

The ajax function :

$(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");
        });

    });


});  

and the 2 php functions to verify the data and send the mail :

<?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;
    }

}

?>  

However I've been stuck at step 1 : My php function is unable to retrieve the data from the file input, it seems like ajax isn't sending the informations regarding this input field.
Php returns Undefined index: contact-attachment.

Can anyone guide/help me through this ? What is wrong with my current code ?

  • 写回答

1条回答 默认 最新

  • dongqu9917 2017-02-14 18:39
    关注

    You form tag doesn't contain all attributes.

    Replace

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

    with

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

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接