Содержание файла index.php
:
<form id="visa-form" method="post" action="mail.php" enctype="multipart/form-data">
<div class="form-group">
<label>ФИО</label>
<input type="text" name="user_fullname" class="form-control" required/>
</div>
<div class="form-group">
<label>Пол</label>
<select name="user_gender" class="form-control">
<option value="Мужской">Мужской</option>
<option value="Женский">Женский</option>
</select>
</div>
<div class="form-group">
<label>Номер телефона</label>
<input type="text" name="user_phone" class="form-control" pattern="\d*" required/>
</div>
<div class="form-group">
<label>Эл. почта</label>
<input type="email" name="user_email" class="form-control" required/>
</div>
<div class="form-group">
<label>Место работы</label>
<input type="text" name="user_workplace" class="form-control" required/>
</div>
<div class="form-group" align="center">
<input id="send-visa-form" type="submit" name="submit" value="Отправить заявку" class="btn btn-info" />
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="main.js"></script>
Содержание файла main.js
:
document.addEventListener('DOMContentLoaded', function() {
alert("yup");
$(function() {
$('#visa-form').submit(function(e) {
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function() {
alert(`success: ${$form.attr("method")} ${$form.attr("action")}`);
}).fail(function() {
alert(`success: ${$form.attr("method")} ${$form.attr("action")}`);
});
//отмена действия по умолчанию для кнопки submit
e.preventDefault();
});
});
});
Содержание файла mail.php
:
<?php
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
$mail = new PHPMailer;
$mail->CharSet = "utf-8";
try
{
if(isset($_POST["submit"]))
{
$message = '
Name: ' . $_POST["user_fullname"] . '
Gender: ' . $_POST['user_gender'] . '
Phone: ' . $_POST["user_phone"] . '
Email: ' . $_POST["user_email"] . '
Workplace: ' . $_POST["user_workplace"] . '
';
$mail->IsSMTP();
$mail->Host = 'smtp.mail.ru';
$mail->Port = '465';
$mail->SMTPAuth = true;
$mail->Username = 'FromMail@mail.ru';
$mail->Password = 'password';
$mail->SMTPSecure = 'ssl';
$mail->From = 'FromMail@mail.ru';
$mail->FromName = 'FromName';
$mail->AddAddress('MyMail@mail.ru', 'Name');
$mail->IsHTML(true);
$mail->Subject = 'Subject';
$mail->Body = $message;
if($mail->Send())
{
// success
}
else
{
// failure
}
}
}
catch (Exception $error)
{
echo 'Произошла ошибка при отправке запроса: ' . $mail->ErrorInfo;
}
finally
{
// header('location: index.php'); Убрал поскольку возвращал код 302
}
Делаю ajax
запрос на отправку почты, отправка почты (скрипт mail.php
) работает. Т. е. если отключить файл mail.js
и отправить форму, то поля успешно отправляются и письмо приходит на почту. Но если отправить форму с ajax
, то выполняется success
(выводится сообщение об успешном отправлении запроса, НО письмо с данными полей не приходит.
Network
Headers mail.php
Request URL: http://ajaxtest/mail.php
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:80
Referrer Policy: no-referrer-when-downgrade
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Date: Fri, 22 May 2020 07:59:00 GMT
Keep-Alive: timeout=120, max=1000
Server: Apache
Accept: ***
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 308
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: ajaxtest
Origin: http://ajaxtest
Pragma: no-cache
Referer: http://ajaxtest/index.php
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.104
X-Requested-With: XMLHttpRequest
user_fullname: ***** ******* *******
user_gender: *****
user_phone: ***
user_email: ******
user_workplace: *****
mail.php
возвращал код302
, потом я убрал назначениеheader('location: index.php')
и теперь получение возвращает код200
. Но, хех, тем не менее письмо не приходитsuccess: post mail.php
это выводится в алерте