0

I am trying to update an HTML form that sends an email with text message to allow sending attachment using a php file and jQuery validation script.

The form works perfectly when bypassing the validation and set the php file on the action directly. When trying to apply the existing jQuery validation, it fails to send the file over and php file is not being executed. For text input fields $("#fieldname").val() works perfectly but for file type I have tried .val(), files[0], .prop("files")[0] and neither worked.

Please find below my used code and advise (Thank you in advance!):

HTML:

<form method="post" name="apply" id="apply" enctype="multipart/form-data" action="">
    <div class="form-group">
        <input type="text" class="form-control" placeholder="Name" name="name1" id="name1">
    </div>
    <div class="form-group">
        <input type="email" class="form-control" placeholder="Email" placeholder="Name" name="eml1" id="eml1">
    </div>
    <div class="form-group1">
        <div class="fileUpload btns">
            <img src="images/icons/upload.png" alt="image">
            <span>Attach your cv</span>
            <input type="file" class="upload" id="upld" name="upld" />
        </div>
        <button type="submit" class=" btn btn-orange">Submit now</button>
    </div>
</form>

jQuery:

jQuery(document).ready(function($) {
    /*  FORM VALIDATION
    /*----------------------------------------------------*/
    /*-------Contact US-----*/
    $("#apply").validate({
        rules: {
            name1: {
                required: true
            },
            eml1: {
                required: true,
                email: true
            },
            upld: {
                required: true
            },
        },
        submitHandler: function(form) {
            var suburl = 'cvmail.php',
                cName = $("#name1").val(),
                cEml = $("#eml1").val(),
                cComment = $("#upld").files[0];
            $('#apply .form-message').show();
            var data = {
                'formid': 'apply',
                'cust_name': cName,
                'upld': cComment,
                'cust_email': cEml
            };
            $.post(suburl, data, function(response) {
                $('.apply-page-form').html(response);
                $('.apply-page-form').show();
                $('#apply').each(function() {
                    this.reset(); //CLEARS THE FORM AFTER SUBMISSION
                });
            });
            return false;
        }
    });
});

PHP:

<?php
if($_POST && isset($_FILES['upld']) {
    $name=$cust_name=$_POST['cust_name'];
    $email=$_POST['cust_email'];
    $email_to_send_to='info@mydomain.com';
    $cSub=$_POST['cSub'];
    $email_subject ="Candidate CV";
    $message = $_FILES['upld']['name']; //message  

    //Get uploaded file data
    $file_tmp_name    = $_FILES['upld']['tmp_name'];
    $file_name        = $_FILES['upld']['name'];
    $file_size        = $_FILES['upld']['size'];
    $file_type        = $_FILES['upld']['type'];
    $file_error       = $_FILES['upld']['error'];

    if($file_error > 0) {
        die('Upload error or No files uploaded');
    }
    //read from the uploaded file & base64_encode content for the mail
    $handle = fopen($file_tmp_name, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $encoded_content = chunk_split(base64_encode($content));

    $boundary = md5("sanwebe");
    //header
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "From:".$name."\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

    //plain text
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($message));

    //attachment
    $body .= "--$boundary\r\n";
    $body .="Content-Type: $file_type; name=".$file_name."\r\n";
    $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
    $body .="Content-Transfer-Encoding: base64\r\n";
    $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
    $body .= $encoded_content;

    $ret = @mail($email_to_send_to,$email_subject, $body, $headers);
    if($ret) {
        //output success or failure messages     
        die('Thank you for your email');
    } else {
        die('Could not send mail! Please check your PHP mail configuration.');  
    }
}
Manoj Sharma
  • 1,467
  • 2
  • 12
  • 20
  • Possible duplicate of [How to use FormData for ajax file upload](http://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload) – Masivuye Cokile Jan 17 '17 at 08:10

2 Answers2

0

You have to use the Form Data to get the uploaded file. There is an answer for this in this link

Community
  • 1
  • 1
G. Mansour
  • 656
  • 6
  • 14
0

HTML:

  1. Change your name attributes for the "name" and "email" to match the ones you expect in the php file. i.e: change name="name1" to name="cust_name" and do the same for the email.

Javascript

  1. Don't manual form the "data" object rather use this var data = new FormData($("#file_upload_form")[0]);
  2. Since this is not a simple text post but includes a file I would suggest you used the longer version of ajax post as something like this:

$.ajax({
 type: "POST",
 url: suburl,
 data: data,
 contentType: false,
 processData: false,
 success: function(response) {
  $('.apply-page-form').html(response);
  $('.apply-page-form').show();
  $('#apply').each(function() {
   this.reset(); //CLEARS THE FORM AFTER SUBMISSION
  });
 }
});
  1. Note the two parameters in the ajax post setting contentType: false,processData: false,. These are necessary when sending files via ajax.

PHP

  1. Your php has an error on the first line. You missing a closing bracket ")".
  2. Where is the "cSub" variable coming from? It just comes out of nowhere. Moreover you don't seem to use it anywhere
Zuks
  • 1,000
  • 9
  • 18
  • Thanks a lot Zuks, it works now, as for the the missing bracket it was removed when I was posting and copying the code. As for the cSub i have added this during some attempts to debug and trying different solutions. Thanks a lot for the professional feedback and suggestion you made my day! – Omar Mughrabi Jan 17 '17 at 12:46