1

I've made a contact form which works, but now I need it to be able to send an attachment too. I have found some examples but I cannot get them to work with my existing code. I'd prefer to keep as much of the form intact as the css is the way I'd like it. I've omitted the the captcha and css in the code below.

<div class="contact-box" id="contact-form">
    <div class="contact-form">
        <form name="contact-form" action="">
            <div class="name">
                <span class="fa fa-user"></span>
                <input id="name" placeholder="Name">
                <label class="error" for="name" id="name_error"><i class="fa fa-exclamation-triangle"></i>Please enter your name.</label>
            </div>
            <div class="email">
                <span class="fa fa-envelope"></span>
                <input id="email" placeholder="Email">
                <label class="error" for="email" id="email_error"><i class="fa fa-exclamation-triangle"></i>Please enter your email address.</label>
            </div>
            <div class="message">
                <span class="fa fa-pencil"></span>
                <textarea id="message" placeholder="Your Message"></textarea>
                <label class="error" for="message" id="message_error"><i class="fa fa-exclamation-triangle"></i>Please enter your message</label>
            </div>
            <label class="attachment">
                <input type="file" id="fileattachment"/>
                <span>Upload Booking Request Form</span>
            </label>
            <div class="submit">
                <input type="submit" name="submit" class="buttonsubmit" id="contact" value="Send">
            </div>

        </form>
    </div>
</div>
<div class="contact-box">
    <div class="contact-confirmation">
        <i class="fa fa-paper-plane"></i>
        <h3>Thanks for your message.</h3>
        <h4>We'll be in touch soon!</h4></div>
</div>

<script>
    $(function() {
        //Hide send confirmation
        $(".contact-confirmation").hide();

        //Validate form
        $('.error').hide();
        $("input#contact").click(function() {
            $('.error').hide();

            var name = $("input#name").val();
            if (name == "") {
                $("label#name_error").show();
                $("input#name").focus();
                return false;
            }

            var email = $("input#email").val();
            if (email == "") {
                $("label#email_error").show();
                $("input#email").focus();
                return false;
            }

            var message = $("textarea#message").val();
            if (message == "") {
                $("label#message_error").show();
                $("textarea#message").focus();
                return false;
            }

            //Attachment part???
            var attachment = $("#fileattachment")[0].files

            //Send form
            var dataString = 'name=' + name + '&email=' + email + '&message=' + message + '&attachment=' + attachment;
            jQuery.ajax({
                type: "POST",
                url: "processemail.php",
                data: dataString,
                success: function() {
                    jQuery(".contact-confirmation").fadeIn(1000);
                    jQuery(".contact-form").hide();
                }
            });
            return false;
        });
    });                 

</script>


//processemail.php

<?php

$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$sendto = $_POST["sendto"];

$sendto = 'overhere@example.com';

$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";  

$message = '<html><body><strong>From: </strong>' . $name . '<br /><strong>Email: </strong>' . $email . '<br /><br /><strong>Message: </strong><br />' . $message . '</body></html>';

mail($sendto, $subject, $message, $headers);

?>
RobertN
  • 41
  • 1
  • 6
  • Is more simple submit form with file type and return to the page.. – Maxi Schvindt Feb 16 '16 at 23:30
  • I agree with @Cuchu - AJAX file upload, while nice, is not necessary for everything. If they were doing a bunch of other stuff in a database front-end designed for web, I might let them AJAX up a couple files so they don't have to leave the front-end page, but if you're just giving them a success message after uploading a form, it's easier to just submit the form normally and look at the $_FILES array in PHP, perform your server operations while they wait, then put them on a success or failure page with a header after. –  Feb 16 '16 at 23:35
  • 1
    Possible duplicate of [jQuery Ajax File Upload](http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – nakashu Feb 16 '16 at 23:36
  • As I posted this I was thinking the same, that maybe I should just use a simple submit form. I was hoping it would be a simple addition but at this point I feel like I've spent too much time on something that is not strictly necessary. – RobertN Feb 16 '16 at 23:43

2 Answers2

2

HTML with your form but some modifications. I use button submit and in the php, check POST and FILES variables. You need copy FILE to path. Find in google how copy file $_FILES to path.

    <html>
<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>


<div class="contact-box" id="contact-form">
    <div class="contact-form">
        <form id="data" method="post" enctype="multipart/form-data">
        <!--<form name="contact-form" action=""> -->
            <div class="name">
                <span class="fa fa-user"></span>
                <input id="name" placeholder="Name" name="name">
                <label class="error" for="name" id="name_error"><i class="fa fa-exclamation-triangle"></i>Please enter your name.</label>
            </div>
            <div class="email">
                <span class="fa fa-envelope"></span>
                <input id="email" placeholder="Email" name="email">
                <label class="error" for="email" id="email_error"><i class="fa fa-exclamation-triangle"></i>Please enter your email address.</label>
            </div>
            <div class="message">
                <span class="fa fa-pencil"></span>
                <textarea id="message" placeholder="Your Message" name="message"></textarea>
                <label class="error" for="message" id="message_error"><i class="fa fa-exclamation-triangle"></i>Please enter your message</label>
            </div>
            <label class="attachment">
                <input type="file" id="fileattachment" name="file"/>
                <span>Upload Booking Request Form</span>
            </label>
            <div class="submit">
                <input type="submit" name="submit" class="buttonsubmit" id="contact" value="Send">
            </div>
            <button type="submit">Go</button>

        </form>
    </div>
</div>
<div class="contact-box">
    <div class="contact-confirmation">
        <i class="fa fa-paper-plane"></i>
        <h3>Thanks for your message.</h3>
        <h4>We'll be in touch soon!</h4></div>
</div>

<script>
    $(function() {
        //Hide send confirmation
        $(".contact-confirmation").hide();

        //Validate form
        $('.error').hide();
        /*
        $("input#contact").click(function() {
            $('.error').hide();

            var name = $("input#name").val();
            if (name == "") {
                $("label#name_error").show();
                $("input#name").focus();
                return false;
            }

            var email = $("input#email").val();
            if (email == "") {
                $("label#email_error").show();
                $("input#email").focus();
                return false;
            }

            var message = $("textarea#message").val();
            if (message == "") {
                $("label#message_error").show();
                $("textarea#message").focus();
                return false;
            }

            //Attachment part???
            var attachment = $("#fileattachment")[0].files

            //Send form
            var dataString = 'name=' + name + '&email=' + email + '&message=' + message + '&attachment=' + attachment;



    }); 
*/

    $("form#data").submit(function(){

console.log($(this));
    var formData = new FormData($(this)[0]);

    $.ajax({
        url : 'processemail.php',
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});
});                

</script>

</body>
</html>

And in the php

<?php


//var_dump($_POST);
//var_dump($_FILES);

$uploads_dir = ""; /* local path */
if(isset($_FILES['file']) && ($_FILES['file']['error'] == 0) ) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "{$uploads_dir}{$name}");
}

$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
//$sendto = $_POST["sendto"];

$sendto = 'overhere@example.com';

$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";  

$message = '<html><body><strong>From: </strong>' . $name . '<br /><strong>Email: </strong>' . $email . '<br /><br /><strong>Message: </strong><br />' . $message . '</body></html>';

mail($sendto, $subject, $message, $headers);

?>
Maxi Schvindt
  • 1,432
  • 1
  • 11
  • 20
  • I tested in my localhost and works! This method implique that use attribute name in the form > input. Names are index in $_POST – Maxi Schvindt Feb 16 '16 at 23:52
  • So I look at both of yours and Ashish's solutions. I did not know you could collect the form data so easily. The form does send (as it already did) but still without the attachment. I have searched google for how to copy file $_FILES to path but I am a little lost with what is happening at this stage and not really sure what I am even searching for? – RobertN Feb 17 '16 at 16:12
  • Hi, with this mode, php copy file to /tmp dir.. you need move the file that info locate in $_FILES to your path. – Maxi Schvindt Feb 17 '16 at 16:16
  • Check the code again, i edit the php and add copy file to local pat. – Maxi Schvindt Feb 17 '16 at 16:27
  • add $uploads_dir www-data:www-data owner and 777 – Maxi Schvindt Feb 17 '16 at 16:50
  • Hola. I can sort of see what this is supposed to do but it's just too far beyond me. I don't understand how to refer to the attachment in php file? The other inputs are easy to obtain. – RobertN Feb 17 '16 at 17:01
  • Hablas español por el "hola" – Maxi Schvindt Feb 17 '16 at 17:15
  • Again... see php.net/manual/es/function.move-uploaded-file.php When you upload attachment with form, the files are uploaded to /tmp (case linux) and the info about this are in $_FILES. Then, you move a file /tmp for your path. – Maxi Schvindt Feb 17 '16 at 17:25
  • I tried your latest code but it still does not work for me. The site is running on WP and so I'm not 100% sure if I should place the upload folder in the root or in /wp-content/themes/theme-name/uploads. I tried both and neither worked (should I even expect to see a file in there after trying it?). And, presumably, in the php code the attachment has to be added somewhere to the actual sending part too? And no, no hablo español, I was just trying to be clever. I appreciate your help and hope I'm not taking up to much of your time though! – RobertN Feb 17 '16 at 23:25
1

You need to submit the form using the formData object.

$("form").submit(function(){

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

This should do the job.

Ashish
  • 679
  • 7
  • 19