2

Inside a form I populate some elements with values using php. I have also inside the form some inputs, such as input files and textarea. Αfter having collected all values in JS, I tried to pass them with AJAX in a php file.

I can handle in that php file all the non-file elements but I can't figure out how to send the input file to php script and attach the file to an email.

I tried the FormData method without any luck. Below you can find part of the code that I have develop for now.

Any suggestions to send input file with ajax successfully and how can I handle it in php?

HTML

<form role="form">
    <div class="col-md-7">
        <div class="user-name">
             <span>@</span>
             <h2 id="usr"><?php echo "".$arr['user']['username']; ?></h2>

        </div>
    </div>
    <div id="photoup1" class="">
         <div class="form-group">
             <label for="photo1" class="upimg"><i class="fa fa-upload" aria-hidden="true"></i> Choose a Photo</label>
                    <input type="file" name="photo1" id="photo1">
          </div>
    </div>
</form>

AJAX/JS

jQuery(function() {
        jQuery("#submit").click(function() {

        var error = false;

        var vardata = new Array();

        var obj = {};

        var username = jQuery.trim(jQuery("#usr").text());
        var photo1 = jQuery("#photo1")[0].files[0];     

        console.log(photo1);

        obj['username'] = username;
        obj['photo1'] = photo1;

        vardata.push(obj);


        console.log(vardata);   


if (error==false){
    jQuery("#submit").attr({"disabled" : "true", "value" : "Loading..." });

    jQuery.ajax({
    type: "POST",
    url: "/mailsender.php?dataafter",
    data: {'vardata' : JSON.stringify(vardata)},
    cache: false,             // To unable request pages to be cached
    success: function(){
                jQuery("#submit").remove();
                console.info("Well done!");
    },
    error: function(){
                console.error("There was an error sending the AJAX call...");
    }
});
//end of ajax
}
return false;
    });
});

PHP

<?php

require 'PHPMailerAutoload.php';

if($_POST){


    $mail = new PHPMailer;
    $mail->isSendmail();
    $mail->setFrom('FROM EMAIL', 'First Last');
    $mail->addAddress('MY EMAIL', 'Nick Ivit');
    $mail->Subject = 'PHPMailer file sender 6test';
    $mail->isHTML(true); 



    $request = $_POST['vardata'];
    $r = json_decode($request, true);

    foreach ($r as $key => $value) {
            $username = $value['username'];
        }

    $mail->Body = ''.$username.'';

    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    }else {
        echo "Message sent!";
    }

?>
  • FormData is the only way to do it.What did you try with FormData what failed? Also need to move it in PHP around ... See also: http://stackoverflow.com/a/23981045/2153758 – bwoebi Jul 24 '16 at 21:52

0 Answers0