0

I want to add file upload function to my job application form. For now everything is working, i get a meesage to my mail but i want to add CV upload option. I made input type file for that but i dont know how to take that file and send it to my mail as attachment. Thank u.

This is my AJAX code:

var sucessMessagee = $("#sucessMessage");

$("#contact_form").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
        console.log('Invalid form');
    } else {
        event.preventDefault();
        submitForm();
    }
});


function submitForm(){

    var name = $("#name").val();
    var surname = $('#surname').val();
    var email = $("#email").val();
    var year = $("#year").val();
    var month = $("#month").val();
    var day = $("#day").val();
    var adress = $("#adress").val();
    var phone = $("#phone").val();

    $.ajax({
        type: "POST",
        url: "/php/jobs.php",
        data: "name=" + name + "&surname=" + surname + "&email=" + email + "&year=" + year + "&month=" + month + "&day=" + day + "&adres=" + adress + "&phone=" + phone,
        success : function(text){
            if (text == "success"){
                formSuccess();
            } else {
                console.log('Failed message');
            }
        }
    });
};

function formSuccess(){
    $("#contact_form")[0].reset();
    $("#posao1").css("display", "none");
    showMessage();
    setTimeout(function() {sucessMessagee.css('display', 'none')},4000);
};

function showMessage() {
    sucessMessagee.css('display', 'block');

};

And this is my php code:

<?php
require 'phpmailer/PHPMailerAutoload.php';
$result = $_POST['result'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$adress = $_POST['adress'];
$phone = $_POST['phone'];

/*if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != "") {
  $file = "attachment/" . basename($_FILES['attachment']['name']);
  move_uploaded_file($_FILES['attachment']['tmp_name'], $file);
} else
  $file = "";*/

$mail = new PHPMailer;
$mail->setFrom($email, 'Prijava za posao');
$mail->addAddress('luka9825@hotmail.com', 'Office');

$mail->Subject  = 'Prijava za posao sa sajta proenterijer.rs';
$mail->Body = "Ime i prezime: $name $surname
                \nDatum rođenja: $day.$month.$year  
                \nAdresa stanovanja: $adress
                \nKontakt telefon: $phone
                \nE-Mail adresa: $email";
if(!$mail->send()) {

} else {
  echo "success";
}
?>
Lule
  • 95
  • 2
  • 7

2 Answers2

0

You will have to need a slight modification to your submitForm() function as follows:

function submitForm(){

    var name = $("#name").val();
    var surname = $('#surname').val();
    var email = $("#email").val();
    var year = $("#year").val();
    var month = $("#month").val();
    var day = $("#day").val();
    var adress = $("#adress").val();
    var phone = $("#phone").val();
    var form_data = new FormData();
    form_data.append('file', $('#ID_OF_YOUR_FILE_INPUT').prop('files')[0]);
    form_data.append('name',name);
    form_data.append('surname',surname);
    form_data.append('email',email);
    form_data.append('year',year);
    form_data.append('month',month);
    form_data.append('day',day);
    form_data.append('adress',adress);
    form_data.append('phone',phone);
    $.ajax({
    type: "POST",
    url: "/php/jobs.php",
    dataType: 'text',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,
    success : function(text){
        if (text == "success"){
        formSuccess();
        } else {
        console.log('Failed message');
        }
    }
    });
};

And your PHP would have to be modified to something like:

<?php
require 'phpmailer/PHPMailerAutoload.php';
$result = $_POST['result'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$adress = $_POST['adress'];
$phone = $_POST['phone'];
$mail_attachment = $_FILES['file'];  // Observe, you don't have to upload the file to your server


$mail = new PHPMailer;
$mail->setFrom($email, 'Prijava za posao');
$mail->addAddress('luka9825@hotmail.com', 'Office');
$mail->addAttachment($mail_attachment);
$mail->Subject  = 'Prijava za posao sa sajta proenterijer.rs';
$mail->Body = "Ime i prezime: $name $surname
        \nDatum rođenja: $day.$month.$year  
        \nAdresa stanovanja: $adress
        \nKontakt telefon: $phone
        \nE-Mail adresa: $email";
if(!$mail->send()) {

} else {
  echo "success";
}
?>
Manikiran
  • 2,618
  • 1
  • 23
  • 39
  • I get this error "Cannot read property '0' of undefined" for this line of code "form_data.append('file', $('#file').prop('files')[0]);" in form submit function. – Lule Jul 28 '18 at 22:22
  • I believe you are not using a proper file input, or you are not referring to the actual file input. Please refer to https://stackoverflow.com/questions/37892426/uncaught-typeerror-cannot-read-property-0-of-undefined – Manikiran Jul 29 '18 at 10:36
  • Fixed it, but still not getting attacment in email, only regular data. – Lule Jul 29 '18 at 11:16
  • Ok try, uploading the file to the server and passing the PATH of the uploaded file as an argument, like: `$mail->addAttachment($UPLOADED_FILE_PATH);` – Manikiran Jul 29 '18 at 11:55
0
// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

    $.ajax({
        url: 'submit.php?files',
        type: 'POST',
        data: data + "name=" + name + "&surname=" + surname + "&email=" + email + "&year=" + year + "&month=" + month + "&day=" + day + "&adres=" + adress + "&phone=" + phone,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                submitForm(event, data);
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            // STOP LOADING SPINNER
        }
    });
}

Now you can get the file from $_GET['files'] in php and then use that to send through the email. Add

defiant
  • 3,161
  • 11
  • 41
  • 65