The attached file is not sent. From the data forms come, but not the file itself. How do I pass the $_FILES variable to the AJAX ???

HTML forms

 <form action="" name="send-form" id="send-form" enctype="multipart/form-data"> <div class="input-line"> <input type="text" required name="email" placeholder=""> </div> <div class="input-line"> <input type="text" required name="search-name" placeholder=""> </div> <div class="input-line"> <input type="file" id="photo-file" name="photo" placeholder=""> </div> </form> 

Js

 $('#send-form').submit(function () { var form_data = $(this).serialize(); $.ajax({ type: "POST", url: "mail.php", data: form_data, success: function() { } }); return false; }); 

Php handler

 $mail->isSMTP(); $mail->Host = 'smtp.mail.ru'; $mail->SMTPAuth = true; $mail->Username = ''; $mail->Password = ''; $mail->SMTPSecure = 'ssl'; $mail->Port = 465; //Recipients $mail->setFrom(''); $mail->addAddress($_POST['email']); //Attachments $mail->addAttachment($_FILES["photo"]["tmp_name"],$_FILES["photo"]["name"]); //Content $mail->isHTML(true); $mail->Subject = 'Заявка c сайта'; $mail->Body = '<html> <head> <title>'.$subject.'</title> </head> <body> <p>Почта для связи: '.$_POST['email'].'</p> <p>Имя для поиска: '.$_POST['search-name'].'</p> </body> </html>'; $mail->AltBody = ''; $mail->send(); echo 'Сообщение успешно отправлено'; } catch (Exception $e) { echo 'Не удалось отправить сообщение ', $mail->ErrorInfo; } 

    1 answer 1

     $('#send-form').submit(function(e) { var $file = $('#photo-file'), $email = $('[name="email"]'), $search_name = $('[name="search-name"]'), frm = new FormData; frm.append('photo', $file.get(0).files); frm.append('email', $email); frm.append('search-name', $search_name); $.ajax({ type: "POST", url: "mail.php", data: frm, success: function() {} }); }) 
    • frm.append ('photo', $ file.files [0]); - on this line gives Cannot read property '0' of undefined - Vladimir
    • frm.append ('photo', $ file.prop ('files') [0]) - tried as in another solution, then the Illegal invocation error is generally on the line with $ .ajax ({ - Vladimir
    • @Vladimir yes, I made a mistake there, changed the answer. - Kirill Korushkin
    • added processData: false, contentType: false, - the Illegal invocation error disappeared, now I can’t set the email address via $ _POST [email] and there is still no attachment file. - Vladimir
    • And messages come in the format [object Object] - Vladimir