0

помогите, не отправляется форма отправки на почту.

Вот PHP

<?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->setFrom('[email protected]', 'Илья Дубиневич');
    //Кому отправить
    $mail->addAddress('[email protected]');
    // Тема письма
    $mail->Subject = 'Привет, новая заявка!';

    //Тело письма
    $body = '<h1>Встречайте супер письмо</h1>';

    if(trim(!empty($_POST['name']))){
        $body.='<p><strong>Имя:</strong> '.$_POST['name'].'</p>';
    }
    if(trim(!empty($_POST['message']))){
        $body.='<p><strong>Сообщение:</strong> '.$_POST['message'].'</p>';
    }

    //Отправляем
    if (!$mail->send()) {
        echo 'Error';
    } else {
        header('location: thank-you.html');
    }

    $response = ['message' => $message];

    header('Content-type: application/json');
    echo json_encode($response);
?>

Вот JS

'use strict';

document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('form');
    const formOrder = document.getElementById('form-order');
    form.addEventListener('submit', formSend);
    formOrder.addEventListener('submit', formSend);

    async function formSend(e) {
        e.preventDefault();

        const error = formValidate(form);

        const formData = new FormData(form);
        const bodyPopup = document.querySelector('.js-modal-container');

        if (error === 0) {
            bodyPopup.classList.add('_sending')
            let response = await fetch('sendmail.php', {
               method: 'POST',
               body: formData
            })
            if (response.ok) {
                const result = await response.json()
                alert(result.message);
                form.reset();
                bodyPopup.classList.remove('_sending');
            } else {
                alert('Ошибка!')
                bodyPopup.classList.remove('_sending');
            }
        } else {
            alert('Заполните поля');
        }
    }

    function formValidate(form) {
        let error = 0;
        let formReq = document.querySelectorAll('._reg')
        console.log(form);
        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');
    }

    //Тест email
    function emailTest(input) {
        return !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(input.value);
    }
})

Заранее спасибо.

3
  • Ну, как минимум делать редирект на html-страницу и пытаться парсить её как json - изначально неудачная идея
    – andreymal
    25 окт 2020 в 17:04
  • я не очень в этом разибраюсь, и делал все по гайду, но почему-то, не очень) можно ли как-нибудь изменить это так, что-бы работало?
    – Jrac
    25 окт 2020 в 17:05
  • Блок кода после «Отправляем» ломает вам JSON
    – vp_arth
    25 окт 2020 в 17:11

1 ответ 1

1

Если скрипт должен возвращать json, он не должен выводить ничего больше, ни echo, ни Location: xxx

//Отправляем
$response = ['message' => $message];
if (!$mail->send()) {
    $response['error'] = 'Email sending error';
}


header('Content-type: application/json');
echo json_encode($response);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.