简体   繁体   中英

Send an input field of type file over jQuery post

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

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

HTML:

  1. Change your name attributes for the "name" and "email" to match the ones you expect in the php file. ie: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM