Answer the question
In order to leave comments, you need to log in
Phpmailer + ajax + jquery, form completion, how to check if the field is filled?
I'm trying to improve the form.
Sending happens through Phpmailer .
My js for the form is made in such a way that it is not attached to the form, how can I bind it to a specific form by id?
Or it makes no sense, because when I click on the submit button, I have a request inside the form, and then it goes to js.
How to display an error if the field is not filled in, let's apply a class to the fields that need to be filled in so that they are highlighted in red, so as not to display for each field in the form, they say fill in the full name, fill in the phone number, etc.
At the moment, nothing comes out of me if the fields are empty, but stupidly sends and displays a message that everything is ok.
The form itself.
<form method="post" id="callback" onsubmit="send(event, 'callback.php')">
<input type="text" name="f_phone" class="f_phone" placeholder="+7 (___) ___-____">
<button type="submit">Перезвонить мне</button>
</form>
<script>
function send(event, php) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var req = new XMLHttpRequest();
req.open('POST', php, true);
req.onload = function() {
if (req.status >= 200 && req.status < 400) {
json = JSON.parse(this.response);
console.log(json);
if (json.result == "success") {
alert("Сообщение отправлено, в ближайшее время Вам перезвонит менеджер.");
$('#callback')[0].reset(); //чистим заполненные поля в форме
} else {
alert("Ошибка. Сообщение не отправлено, попробуйте повторить действия позднее.");
}
// Если не удалось связаться с php файлом
} else {
alert("Ошибка сервера. Номер: " + req.status);
}
};
// Если не удалось отправить запрос. Стоит блок на хостинге
req.onerror = function() {
alert("Ошибка отправки запроса");
};
req.send(new FormData(event.target));
}
</script>
<?php
require_once __DIR__ . "/vendor/autoload.php";
$f_phone = $_POST['f_phone'];
$textBase = "Номер телефона: " . $f_phone . "";
$textAdmin = "Новый запрос обратного звонка от " . date("Y-m-d H:i:s") . " по времени сервера, данные
" . $textBase . "
";
try {
$text_html = nl2br($textAdmin);
$sPort = 465;
$sSecure = "ssl";
$sUsername = "0000000000";
$sPassword = "00000000000";
$sHost = "smtp.yandex.ru";
$sFromEmail = "0000000000";
$sDomain = "0000000000000";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = $sHost;
$mail->Port = $sPort;
$mail->SMTPAuth = true;
$mail->SMTPSecure = $sSecure;
$mail->Username = $sUsername;
$mail->Password = $sPassword;
$mail->setFrom($sFromEmail, $sDomain);
$mail->addAddress('0000000000000'); //сюда отправляем
$mail->Subject = 'Новый запрос звонка на '.$sDomain;
$mail->msgHTML($text_html);
$mail->AltBody = $textAdmin;
$mail->CharSet = "utf-8";
// Проверяем отравленность сообщения
if ($mail->send()) {$result = "success";}
else {$result = "error";}
} catch (Exception $e) {
$result = "error";
$status = "Сообщение не было отправлено. Причина ошибки: {$mail->ErrorInfo}";
}
// Отображение результата
echo json_encode(["result" => $result, "resultfile" => $rfile, "status" => $status]);
?>
Answer the question
In order to leave comments, you need to log in
Found a solution to my problem:
$(".valpro").each(function() {
if (!$(this).val()) {
$(this).addClass('validform');
errors = true;
alert('Заполните все важные поля.');
} else {
$(this).removeClass('validform');
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question