【问题标题】:Change the color of messages when submitting a form using Ajax使用 Ajax 提交表单时更改消息的颜色
【发布时间】:2020-03-06 07:52:43
【问题描述】:

有人可以帮助我吗?有一个用于将消息发送到电子邮件的工作表单。

<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;

//protection against 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);


//Issues an error if the download size exceeds the limit set by the server
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;
}

一切正常,但所有消息都显示为红色,因为# answer 的样式设置为红色。但有必要在成功提交表单的情况下以绿色显示消息,如果出现错误 - 以红色显示。尝试添加:

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 中正确进行切换,以便消息在成功发送时显示为绿色,以及为什么在 handler.php 中未应用 css 样式。

【问题讨论】:

  • echo 'Phone doesn't match format.';需要转义'echo 'Phone doesn\'t match format.';
  • 好的,但这不是我需要的。
  • 好吧,如果 PHP 文件不正确,你会得到 500 响应,这会触发代码的错误部分。另外,我看不出你在哪里将$result 设置为'ok'
  • 我尝试将 $result 设置为 'ok',但我不知道如何正确设置。

标签: php jquery css ajax


【解决方案1】:

它永远不会输入成功代码,因为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);
        },

【讨论】:

  • 非常感谢。这有效:` if (result.includes ('successfully')) `.
  • 这可以通过 $result as 'ok '来实现吗?
  • 嗯,它可以,但是$result 是您也可以输出为显示的文本的内容。您可以创建一个数组并返回一个数组,其中状态为'ok' 和消息。
【解决方案2】:

还有一个。

联系邮箱:

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

handler.php:

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


if (!Validator::isAjax() || !Validator::isPost()) {
    $data['error'] = 'Access is forbidden!';
    echo json_encode($data);
    exit;
}

$data = array();

$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;


//protection against 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);


//Issues an error if the download size exceeds the limit set by the server
if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0) {
    $data['error'] = "CONTENT SIZE EXCEEDS THE LIMIT";
    echo json_encode($data);
    exit;
}


if (empty($name) || empty($email) || empty($phone) || empty($message)) {
    $data['error'] = 'All fields are required.';
    echo json_encode($data);
    exit;
}

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


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

if (!Validator::isValidPhone($phone)) {
    $data['error'] = 'Phone doesn\'t match format.';
    echo json_encode($data);
    exit;
}


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

ajax:

$(function() {

  $('#form').on('submit', function(e) {


    e.preventDefault();

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

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


    data: new FormData(this),

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

        success: function(data) {
            loader.fadeOut(300, function() {
            if (data.error) {
            answer.text(data.error).addClass('error');
        }   else {
            answer.text(data.success).addClass('success');
        }
            });
            form[0].reset();
            button.attr('disabled', true);
            },

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

        });

    });

  });

在ajax这个方法中一定要加上dataType: "json"。

【讨论】:

    【解决方案3】:

    另一种方式。

    ContactMailer.php:

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

    handler.php:

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

    ajax:

    success: function(data) {
                loader.fadeOut(300, function() {
                if (data === "yes") {
                answer.text("Your message was sent successfully.").addClass('success');
              } else {
                answer.text(data).addClass('error');
              }
              });
                form[0].reset();
                button.attr('disabled', true);
            },
    

    为了在调用ajax之前正确切换,我们也删除了答案。 removeClass('error success') 类如上例,否则将同时添加两个类到答案中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 2014-12-10
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多