Answer the question
In order to leave comments, you need to log in
How to connect PHPMailer to Wordpress?
Greetings! I pulled my layout on cms wordpress, then I wanted to connect work with forms, but I don’t want to use any plugin, because it seemed to me that they heavily load the site and plus there is crap with their styles. I found a vidos on YouTube on which I wrote the codes below, uploaded everything to the hosting, and it gives me the following error: POST multi-faced.tw1.ru/sendmail.php 404 (Not Found). As I understand it, he does not see this file, which means that in js, where FETCH sets the path, you need to specify it correctly somehow, but I don’t understand how. Save me, this is my first time doing this ((
JS code:
function submitForm() {
document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('form');
form.addEventListener('submit', formSend);
async function formSend(e) {
e.preventDefault();
let error = formValidate(form);
let formData = new FormData(form);
// formData.append('image', formImage.files[0]);
if (error === 0) {
form.classList.add('_sending');
let response = await fetch('sendmail.php', {
method: 'POST',
body: formData
});
if (response.ok) {
let result = await response.json();
alert(result.message);
// formPreview.innerHTML = '';
form.reset();
form.classList.remove('_sending');
} else {
alert('Ошибка!');
form.classList.remove('_sending');
}
} else {
alert('Сначала заполните поле')
}
}
function formValidate(form) {
let error = 0;
let formReq = document.querySelectorAll('._req');
for (let index = 0; index < formReq.length; index++) {
const input = formReq[index];
formRemoveError(input);
if (input.classList.contains('_email')) {
if (emailTest(input)) {
formAddError(input);
error++;
}
} else if (input.getAttribute('type') === 'checkbox' && input.checked === false) {
formAddError(input);
error++;
} else {
if (input.value === '') {
formAddError(input);
error++;
}
}
}
return error;
}
function formAddError(input) {
input.parentElement.classList.add('_error');
input.classList.add('_error');
}
function formRemoveError(input) {
input.parentElement.classList.remove('_error');
input.classList.remove('_error');
}
function emailTest(input) {
return !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(input.value);
}
// const formImage = document.getElementById('formImage');
// const formPreview = document.getElementById('formPreview');
// formImage.addEventListener('change', () => {
// uploadFile(formImage.files[0]);
// });
// function uploadFile(file) {
// if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
// alert('Разрешены только изображения');
// formImage.value = '';
// return;
// }
// if (file.size > 2 * 1024 * 1024) {
// alert('Файл должен быть менее 2 МБ.');
// return;
// }
// let reader = new FileReader();
// reader.onload = function (e) {
// formPreview.innerHTML = `<img src="${e.target.result}" alt="Фото">`;
// };
// reader.onerror = function (e) {
// alert('Ошибка');
// };
// reader.readAsDataURL(file);
// }
});
}
submitForm();
<form action="#" id="form" class="subscribe__form">
<div class="subscribe__input-wrap">
<input id="formEmail" placeholder="Type Your Email Address" class="subscribe__input _req _email" type="text" name="email">
<div class="subscribe__button-wrap">
<button class="subscribe__btn btn" type="submit">Send now</button>
</div>
</div>
</form>
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
$mail = new PHPMailer(true);
$mail->Charset = 'UTF-8';
$mail->setLanguage('ru', 'phpmailer/language/');
$mail->IsHTML(true);
// От кого письмо
$mail->setForm('[email protected]', 'Фрилансер по жизни');
//Кому отправить
$mail->addAddress('[email protected]');
//Тема письма
$mail->Subject = 'Привет! Это "Фрилансер по жизни"';
//Тело письма
$body = '<h1>Встречайте супер письмо!<h1>';
if (trim(!empty($_POST['email']))) {
$body.='<p><strong>E-mail:</strong> '.$_POST['email'].'</p>';
}
$mail->Body = $body;
//Отправляем
if (!$mail->send()) {
$message = 'Ошибка';
} else {
$message = 'Данные отправлены';
}
$response = ['mesaage' => $message];
header('Content-type: application/json');
echo json_encode($response);
?>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question