Изменить цвет сообщений при отправке формы с помощью Ajax - PullRequest
0 голосов
/ 10 ноября 2019

Кто-нибудь может мне помочь? Существует рабочая форма для отправки сообщений на электронную почту.

<form enctype="multipart/form-data" role="form" id="form" method="post" action="handler.php">
        <div class="form-row">
            <div class="form-group col-sm-6">
                <label for="name" class="nameForInput">Name:</label>
                <input type="text" name="name" class="form-control" id="name" placeholder="Enter name" >
            </div>
            <div class="form-group col-sm-6">
                <label for="email" class="nameForInput">Email:</label>
                <input type="mail" name="email" class="form-control" id="email" placeholder="Enter email" >
            </div>
            </div>
            <div class="form-group">
                <label for="phone" class="nameForInput">Phone:</label>
                <input class="form-control phone" name="phone" type="text" placeholder="+3 (000) 000-00-00" >
            </div>
        <div class="form-group">
            <label for="message" class="nameForInput">Message:</label>
            <textarea id="message" class="form-control" name="message" rows="5"placeholder="Enter your message" ></textarea>
        </div>
        <div class="form-group">
        <label for="myfile" class="file-label left">
          <img src="img/upload.svg" alt="">
          <p class="amount">To attach files</p>
        </label>
        <input type="file" class="my" id="myfile" name="myfile[]" multiple>
        </div>
        <div class="form-group">
                <input id="check" name="check" checked type="checkbox">
                <span class="check-text">I confirm my consent to the processing of personal data</span>
</div>
        <button type="submit" class="btn btn-success btn-lg">Send</button>
       <div class="result">
                <span id="answer"></span>
                <span id="loader"><img src="img/loader.gif" alt=""></span>
            </div>
    </form>

ajax:

var form = $('#form'),
        button = $('.btn'),
        answer = $('#answer'),
        loader = $('#loader');

    $.ajax({
        url: 'handler.php',
        type: 'POST',
        contentType: false,
        processData: false,

    data: new FormData(this),

        beforeSend: function() {
            answer.empty();
            button.attr('disabled', true).css('margin-bottom', '20px');
            loader.fadeIn();
            },

        success: function(result) {
            loader.fadeOut(300, function() {
            answer.text(result);
            });
            form[0].reset();
            button.attr('disabled', false);
            },

        error: function() {
            loader.fadeOut(300, function() {
            answer.text('An error occurred! Try later.');
            });
            button.attr('disabled', false);
            }
        });
    });
  });

ContactMailer.php:

<?php

class ContactMailer
{
    /**
     * Sender's E-mail
     * @var string
     */
    private static $emailFrom = 'somemail@mail.com';
    /**
     * Recipient's E-mail
     * @var string
     */
    private static $emailTo = 'somemail@mail.com';

    /**
     * Sends an email if the email is sent,
     * Returns TRUE, otherwise FALSE.
     * @param string $name
     * @param string $email
     * @param string $phone
     * @param string $message
     * @return boolean
     */
    public static function send($name, $email, $phone, $message)
    {
        // We form a letter body
        $body = "Name: " . $name . "\nE-mail: " . $email . "\nPhone: " . $phone . "\n\nMessage:\n" . $message;

        // Create PHPMailer object
        $mailer = new PHPMailer(true);
        // Connection settings
        $mailer->isSMTP();
        // Installs the mail server host (Mail.ru: smtp.mail.ru, Google: smtp.gmail.com)
        $mailer->Host = 'smtp.mail.com';
        // Includes SMTP authorization
        $mailer->SMTPAuth = true;
        // Entire login or E-mail
        $mailer->Username = self::$emailFrom;
        // Mailbox Password
        $mailer->Password = '';
        // Protocol of connection
        $mailer->SMTPSecure = '';
        // Port for outgoing mail
        $mailer->Port = '';


        // Establishes coding
        $mailer->CharSet = 'UTF-8';
        // Sets E-mail and sender name
        $mailer->setFrom(self::$emailFrom, $name);
        // Adds recipient 's E-mail
        $mailer->addAddress(self::$emailTo);
        // Control of a HTML-format
        $mailer->isHTML(false);
        // Letter subject
        $mailer->Subject = 'Feedback form completed';
        // Main body of the letter
        $mailer->Body = $body;


    // Send the letter
    if ($mailer->send()) {
        return true;
    }
        return false;
    }
}

handler.php:

<?php

require_once __DIR__ . '/mailer/Validator.php';
require_once __DIR__ . '/mailer/ContactMailer.php';

if (!Validator::isAjax() || !Validator::isPost()) {
    echo 'Access is forbidden!';
    exit;
}

$name = isset($_POST['name']) ? trim(strip_tags($_POST['name'])) : null;
$email = isset($_POST['email']) ? trim(strip_tags($_POST['email'])) : null;
$phone = isset($_POST['phone']) ? trim(strip_tags($_POST['phone'])) : null;
$message = isset($_POST['message']) ? trim(strip_tags($_POST['message'])) : null;

//защита от XSS
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);


//Выдает ошибку, если размер загружаемых файлов превышает лимит установленный сервером
if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0)
    { echo "CONTENT SIZE EXCEEDS THE LIMIT"; 
exit;}


if (empty($name) || empty($email) || empty($phone) || empty($message)) {
    echo 'All fields are required.';
    exit;
}

if (!Validator::isValidName($name)) {
    echo 'Name does not match format (name must contain only letters).';
    exit;
}


if (!Validator::isValidEmail($email)) {
    echo 'E-mail does not conform to the format.';
    exit;
}

if (!Validator::isValidPhone($phone)) {
    echo 'Phone doesn\'t match format.';
    exit;
}


if (ContactMailer::send($name, $email, $phone, $message)) {
    echo htmlspecialchars($name) . ', your message was sent successfully.';
} else {
    echo ' An error occurred! Failed to send message.';
}
exit;

?>

css:

#answer {
 color: #ff5b5b;
}

Все работает, но все сообщения отображаются красным, потому что стили для ответа # установлены красным. Но необходимо, чтобы в случае успешной подачи форм сообщения отображались зеленым цветом, а в случае ошибок - красным. Попытался добавить это:

success: function(result) {

            loader.fadeOut(300, function() {
            if (result === 'ok') {
            answer.text(result).addClass('success');
        }   else {
            answer.text(result).addClass('error');
        }
            });
            form[0].reset();
            button.attr('disabled', false);
            },

css:

.success {
  color: #218838;
}

.error {
  color: #ff5b5b;
}

, но всегда добавляется только класс 'error', и, если отправка также успешна. Также попробовал в файле handler.php просто прикрепить стили к сообщению:

if (ContactMailer::send($name, $email, $phone, $message)) {
    echo htmlspecialchars($name) . '<span style="color: #218838;">, your message was sent successfully.</span>';
} else {
    echo 'An error occurred! Failed to send message.';
}
exit;

но ничего не применимо, выдает просто сообщение вместе с тегами:

'<span style="color: #218838;">, your message was sent successfully.</span>'

Хотя, если вы создаете простокакой-то другой php-файл, там сообщение в echo отображается зеленым, в этом файле handler.php не работает.

Кто-то может подсказать, как правильно сделать переключение в Ajax, чтобы сообщение отображалось зеленым, когдауспешно отправлено и почему CSS-стили не применяются в handler.php.

1 Ответ

0 голосов
/ 10 ноября 2019

Он никогда не вводит код для успеха, потому что result никогда не устанавливается на 'ok', а на длинное успешное сообщение.

success: function(result) {
        loader.fadeOut(300, function() {
        if (result.includes('your message was sent successfully')) {
        answer.text(result).addClass('success');
    }   else {
        answer.text(result).addClass('error');
    }
        });
        form[0].reset();
        button.attr('disabled', false);
        },
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...