duanjia1870
duanjia1870
2017-02-14 18:22
浏览 115

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
    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>
    
    点赞 评论

相关推荐