2

I first made my contact form using PHP and the file attachment worked fine. Here is that PHP file:

$from = $_POST["name"];
$email = $_POST["email"];
$topic = $_POST["subject"];
$message = $_POST["message"];
$attachment = $_FILES["attachment"];
$to = //my email
$subject = "New Message";

$headers = "From: Emily's Portfolio";

$tmp_name = $_FILES["attachment"]["tmp_name"];
$type = $_FILES["attachment"]["type"];
$name = $_FILES["attachment"]["name"];
$size = $_FILES["attachment"]["size"];

$message = "From: $from \nEmail: $email \nSubject: $topic \nMessage: \n$message\n";

if (file_exists($tmp_name)) {

    $file = fopen($tmp_name, "r");

    $data = fread($file, filesize($tmp_name));

    fclose($file);


    $randomVal = md5(time());
    $mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";


    $headers .= "\nMIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/mixed;\n" ;
    $headers .= " boundary=\"{$mimeBoundary}\"";

    $message .= "--{$mimeBoundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

    $data = chunk_split(base64_encode($data));

    $message .= "--{$mimeBoundary}\n" . "Content-Type: {$type};\n" . " name=\"{$name}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mimeBoundary}--\n";

}

$back = "#contact";

if (!(empty($from) || empty($email) || empty($message))) {
    if (mail ($to, $subject, $message, $headers)) {
        echo "<p>Your message has been sent! </p>";
        echo "<p><a href=\"javascript:history.go(-1)\" title=\"Go back to previous page\">Go back</a></p>";
    } 
    else {
        echo "<p>Error, please try again.</p>";
        echo "<p><a href=\"javascript:history.go(-1)\" title=\"Go back to previous page\">Go back</a></p>";
    }
} 
else {
    echo "<p>Please fill out all fields.</p>";
    echo "<p><a href=\"javascript:history.go(-1)\" title=\"Go back to previous page\">Go back</a></p>";
}

I then decided I want my form to use ajax so it wouldn't take the user to another page when submitted. I got the form working using ajax without the file attachment, but can't seem to figure out how to incorporate the file attachment.

Here is the PHP for the form w/o attachment:

if ($_POST) {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $topic = $_POST["subject"];
    $message = $_POST["message"];

    $recipient = //my email

    $subject = "New contact from $name";

    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Subject: $topic\n";
    $email_content .= "Message:\n$message\n";

    $email_headers = "From: $name <$email>";

    if (mail($recipient, $subject, $email_content, $email_headers)) {
        echo "Thank You! Your message has been sent.";
    } 
    else {
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

And the JavaScript/Ajax code for it:

$(function() {
var form = $("#ajax-contact");
var formMessages = $("#form-messages");
var input = document.getElementById("attachment");
$(form).submit(function(event) {
    event.preventDefault();
    var formData = $(form).serialize();

    $.ajax({
        type: "POST",
        url: $(form).attr("action"),
        data: formData

    })

    .done(function(response) {
        $(formMessages).removeClass("error");
        $(formMessages).addClass("success");

        $(formMessages).text(response);

        $("#name").val("");
        $("#email").val("");
        $("#message").val("");
        $("#subject").val("");
                })

    .fail(function(data) {
        $(formMessages).removeClass("success");
        $(formMessages).addClass("error");

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

Here's the HTML too if it helps:

<div id="form-messages"></div>
<form id="ajax-contact" method="post" action="mailer.php">
    <section class="half">
        <div class="field">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" >
        </div>
        <div class="field">
            <label for="subject">Subject:</label>
            <input type="text" id="subject" name="subject">
        </div>
    </section>
    <section class="half-right">
        <div class="field" >
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div class="field">
            <label for="file">Attach a File:</label>
            <input name="attachment" type="file" id="attachment">

    </section>
    <div class="field" id="memo">
        <label for="message">Message:</label>
        <textarea id="message" name="message" required></textarea>
    </div>

    <div class="field">
        <button id="button" type="submit">Submit</button>
    </div>
</form>

Can anyone direct me towards information that will allow me to incorporate a file upload into my form that works with Ajax?

Edit: thank you for the link to the other question, but I can't figure out how to incorporate the file upload WITH the email form. I'm very much a beginner, so I don't know how to get the data of the file into one set of data along with the email information. Do I used the FormData object? Would I still need all of the "$_FILES" code in the PHP code?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    Don't build mime emails yourself. Use phpmailer or swiftmailer, both of which will reduce pretty much ALL of that mime-related busyworkd into just a couple lines of code. – Marc B Dec 22 '14 at 19:39
  • The HTML does not seem to be [well-formed](http://en.wikipedia.org/wiki/Well-formed_element) (the "div" containing "Attach a File"). – Peter Mortensen Dec 22 '14 at 20:23

0 Answers0