【问题标题】:AJAX form not displaying succes or error messageAJAX 表单不显示成功或错误消息
【发布时间】:2018-01-22 22:32:32
【问题描述】:

我以前也问过这个问题,但我还是没弄明白。我做了一些改变,但不幸的是我仍然没有得到任何运气。表单本身可以工作,但当用户尝试发送表单时,它也应该显示错误或成功消息。但是它不显示消息,而是发送表单而不显示它。看看我的代码:

HTML

 <form action="" method="POST">
    <ul class="form-style-1">
        <li>
            <input type="text" id="mail-name" name="name" class="field-divided" maxlength="15"  placeholder="Voornaam *" />&nbsp;<input type="text" id="mail-lastname" name="lastname" class="field-divided" maxlength="15" placeholder="Achternaam" >
        </li>
        <li>
            <input type="email" id="mail-email" name="email" placeholder="E-mail *" class="field-long" maxlength="40" >
        </li>
        <li>
            <input type ="text" id="mail-phone" name="phone" placeholder="Telefoonnummer" class="field-long" maxlength = "15">
        </li>
        <li>
            <select name="subject" id="mail-subject" class="field-select" >
            <option disabled value="" selected hidden >--Onderwerp-- *</option>
            <option value="Kennismakingsgesprek">Kennismakingsgesprek</option>
            <option value="Meer informatie">Meer informatie</option>
            <option value="activiteit">Aanmelding activiteit</option>
            <option value="Vraag/klacht">Vraag/klacht</option>
            <option value="Contact">Overig</option>
            </select>
        </li>
        <li>
            <textarea name="information" id="mail-information"  placeholder =" Je bericht *"class="field-long field-textarea" maxlength="2000"></textarea>
        </li>
        <button class="mail-submit" id="mail-submit" type="submit" name="submit">Send e-mail</button>
        <span class="form-message"></span>
    </ul>
</form>

JS(此脚本位于页眉中)

$("#mail-submit").click(function(event){
  event.preventDefault();
  var name = $("#mail-name").val();
  var lastname = $("#mail-lastname").val();
  var email = $("#mail-email").val();
  var phone = $("#mail-phone").val();
  var subject = $("#mail-subject").val();
  var information = $("#mail-information").val();
  $.post("contact.php",
    {
      name: name,
      lastname: lastname,
      email: email,
      phone: phone,
      subject: subject,
      information: information,
      submit: "yes"
    },
    function(data){
        $(".form-message").html( data );
    }
  );
});

PHP(位于 PHP 文件中)

if (isset($_POST['submit'])) {

  $email_to = "#";

  $email_subject = "#";

  $name = $_POST['name'];
  $lastname = $_POST['lastname'];
  $email = $_POST['email'];
  $phone = $_POST['phone'];
  $subject = $_POST['subject'];
  $information = $_POST['information'];

  $errorEmpty = false;
  $errorEmail = false;

  if (empty($name) || empty($email) || empty($subject) || empty($information)) {
    echo "<span class='form-error'>Voer alle velden in!</span>";
    $errorEmpty = true;
  }
  elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "<span class='form-error'>Geef een geldig E-mail!</span>";
    $errorEmail = true;
  }
  else {
    $formcontent=" Naam: $name \n\n Achternaam: $lastname \n\n Email: $email \n\n Telefoon: $phone \n\n Onderwerp: $subject \n\n Informatie: $information";
    $mailheader = "From: ".$_POST["email"]."\r\n";
    $headers = "From: ". htmlspecialchars($_POST['name']) ." <" . $_POST['email'] . ">\r\n";
    $headers .= "Reply-To: " . $_POST['email'] . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    mail($email_to, $subject, $formcontent, $mailheader);
    echo "<span class='form-success'>E-mail has been sent!</span>";
  }
}

这是我使用的 AJAX 脚本:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

【问题讨论】:

标签: javascript php jquery html ajax


【解决方案1】:

我会这样做。我简化了代码以便更好地理解。

选项1:一个文件(contact.php),一个表单,没有ajax,没有onclick事件:

<?php
$emailSent = FALSE;

/*
 * ===================================
 * Run operations upon form submission
 * ===================================
 */
if (isset($_POST['submit'])) {
    /*
     * ==========================
     * Validate the posted values
     * ==========================
     */
    if (!isset($_POST['name']) || empty($_POST['name'])) {
        $errors[] = 'Please provide a name.';
    }

    if (!isset($_POST['email']) || empty($_POST['email'])) {
        $errors[] = 'Please provide an email.';
    } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email.';
    }

    /*
     * ======================================
     * Send the email if all values are valid
     * ======================================
     */
    if (!isset($errors)) {
        $name = $_POST['name'];
        $email = $_POST['email'];

        // Send the email here, using the posted values...

        $emailSent = TRUE;
    }
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>

        <div class="messages">
            <?php
            if (isset($errors)) {
                foreach ($errors as $error) {
                    ?>
                    <div class="error">
                        <?php echo $error; ?>
                    </div>
                    <?php
                }
            } elseif ($emailSent) {
                ?>
                <div class="success">
                    The email was successfully sent.
                </div>
                <?php
            }
            ?>
        </div>

        <form action="" method="POST">
            <input type="text" id="mail-name" name="name" />
            <input type="email" id="mail-email" name="email" />

            <button class="mail-submit" id="mail-submit" type="submit" name="submit">
                Send e-mail
            </button>
        </form>

    </body>
</html>

选项2:两个文件,一个ajax,一个onclick事件,完全没有表单:

contact.php:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#submit').click(function (event) {
                    $.ajax({
                        method: 'post',
                        dataType: 'html',
                        url: 'send-email.php',
                        data: {
                            'name': $('#name').val(),
                            'email': $('#email').val()
                        },
                        success: function (response, textStatus, jqXHR) {
                            $('.messages').html(response);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            var message = 'An error occurred during your request. Please try again, or contact us.';
                            $('.messages').html('<div class="error">' + message + '</error>');
                        }
                    });
                });
            });
        </script>
    </head>
    <body>

        <div class="messages"></div>

        <div class="contact-form">
            <input type="text" id="name" name="name" />
            <input type="email" id="email" name="email" />

            <button type="button" id="submit" name="submit">
                Send e-mail
            </button>
        </div>

    </body>
</html>

发送电子邮件.php:

<?php

$response = '';
$emailSent = FALSE;

/*
 * ==========================
 * Validate the posted values
 * ==========================
 */
if (!isset($_POST['name']) || empty($_POST['name'])) {
    $errors[] = 'Please provide a name.';
}

if (!isset($_POST['email']) || empty($_POST['email'])) {
    $errors[] = 'Please provide an email.';
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Invalid email.';
}

/*
 * ======================================
 * Send the email if all values are valid
 * ======================================
 */
if (!isset($errors)) {
    $name = $_POST['name'];
    $email = $_POST['email'];

    // Send the email here, using the posted values...

    $emailSent = TRUE;
}

/*
 * ==============================================================
 * Assign the corresponding message (with error or success class)
 * ==============================================================
 */
if (isset($errors)) {
    foreach ($errors as $error) {
        $response .= '<div class="error">' . $error . '</div>';
    }
} elseif ($emailSent) {
    $response .= '<div class="success">The email was successfully sent.</div>';
}

/*
 * ==================
 * Print the response
 * ==================
 */
echo $response;

可选:带有客户端验证的选项 1:

您可以在提交前验证表单,如果至少有一个字段无效(空值、错误的电子邮件地址等),您可以停止提交并显示相应的错误消息:

<?php
$emailSent = FALSE;

/*
 * ===================================
 * Run operations upon form submission
 * ===================================
 */
if (isset($_POST['submit'])) {
    /*
     * ==========================
     * Validate the posted values
     * ==========================
     */
    if (!isset($_POST['name']) || empty($_POST['name'])) {
        $errors[] = 'Please provide a name.';
    }

    if (!isset($_POST['email']) || empty($_POST['email'])) {
        $errors[] = 'Please provide an email.';
    } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email.';
    }

    /*
     * ======================================
     * Send the email if all values are valid
     * ======================================
     */
    if (!isset($errors)) {
        $name = $_POST['name'];
        $email = $_POST['email'];

        // Send the email here, using the posted values...

        $emailSent = TRUE;
    }
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                // The form will not submit before all fields are valid.
                $('.contact-form').submit(function (event) {
                    var messages = [];

                    var name = $.trim($('#name').val());
                    var email = $.trim($('#email').val());

                    // Validate user input.
                    if (name === '') {
                        messages.push('Please provide a name.');
                    }

                    if (email === '') {
                        messages.push('Please provide an email.');
                    }

                    // Display the error messages, if any.
                    if (messages.length > 0) {
                        $('.messages').html('');
                        for (var i = 0; i < messages.length; i++) {
                            $('.messages').append('<div class="error">' + messages[i] + '</div>');
                        }

                        // Abort the form submission.
                        return false;
                    }

                    // Continue the form submission.
                    return true;
                });
            });
        </script>
    </head>
    <body>

        <div class="messages">
            <?php
            if (isset($errors)) {
                foreach ($errors as $error) {
                    ?>
                    <div class="error">
                        <?php echo $error; ?>
                    </div>
                    <?php
                }
            } elseif ($emailSent) {
                ?>
                <div class="success">
                    The email was successfully sent.
                </div>
                <?php
            }
            ?>
        </div>

        <form class="contact-form" action="" method="POST">
            <input type="text" id="mail-name" name="name" />
            <input type="email" id="mail-email" name="email" />

            <button class="mail-submit" id="mail-submit" type="submit" name="submit">
                Send e-mail
            </button>
        </form>

    </body>
</html>

当然,对于选项 2,您可以轻松实现这样的验证,方法是在 onclick 处理程序中包含验证代码,如果输入无效则不运行 ajax 请求。

祝你好运!

【讨论】:

  • 我在您编写选项 2 时尝试了选项 1。而且效果很好。我只需要再问一个问题,您推荐使用哪一个?选项 1 或 2?但对于其余的,我很感激你花时间帮助我解决我的问题,非常感谢。
  • @Joe 我很高兴它起作用了,选项 1。实际上,对于这种任务,用户可以同时使用这两个选项。有一个表格,完成它,提交它,刷新(或不刷新)后接收消息,完成。虽然,一方面,如果用户对她/他的 javascript 有一些“问题”(例如 js 被停用等),选项 1 是正确的,因为根本不依赖 js 代码。例如。表单将提交,电子邮件将被发送。
  • @Joe 另一方面,这些天谁对 javascript 有“问题”? :-)) 用户没有激活 js 的日子已经一去不复返了。今天所有的网站都依赖 js 和 jquery。而且,因为第二个选项使用 ajax,所以页面 (contact.php) 根本不会刷新。只会填写消息(发送电子邮件后)。因此,我个人会推荐选项 2。
  • @Joe 我没有阅读您的所有信息...感谢您的赞赏。不客气。
  • @Joe,我用可选代码更新了我的答案。也许将来会对你有所帮助。再见。
【解决方案2】:

这不能放在一个文件中。你需要两个。

像这样尝试......如果有的话,用一些新问题来编辑你的问题。

注意 submit 事件处理程序...而不是点击处理程序。

page.html:

<form action="" method="POST">
  <ul class="form-style-1">
      <li>
          <input type="text" id="mail-name" name="name" class="field-divided" maxlength="15"  placeholder="Voornaam *" />&nbsp;<input type="text" id="mail-lastname" name="lastname" class="field-divided" maxlength="15" placeholder="Achternaam" >
      </li>
      <li>
          <input type="email" id="mail-email" name="email" placeholder="E-mail *" class="field-long" maxlength="40" >
      </li>
      <li>
          <input type ="text" id="mail-phone" name="phone" placeholder="Telefoonnummer" class="field-long" maxlength = "15">
      </li>
      <li>
          <select name="subject" id="mail-subject" class="field-select" >
          <option disabled value="" selected hidden >--Onderwerp-- *</option>
          <option value="Kennismakingsgesprek">Kennismakingsgesprek</option>
          <option value="Meer informatie">Meer informatie</option>
          <option value="activiteit">Aanmelding activiteit</option>
          <option value="Vraag/klacht">Vraag/klacht</option>
          <option value="Contact">Overig</option>
          </select>
      </li>
      <li>
          <textarea name="information" id="mail-information"  placeholder =" Je bericht *"class="field-long field-textarea" maxlength="2000"></textarea>
      </li>
      <button class="mail-submit" id="mail-submit" type="submit" name="submit">Send e-mail</button>
      <span class="form-message"></span>
  </ul>
</form>

<script>

$("form").on("submit",function(event){  // Submit handler!
  event.preventDefault();
  var name = $("#mail-name").val();
  var lastname = $("#mail-lastname").val();
  var email = $("#mail-email").val();
  var phone = $("#mail-phone").val();
  var subject = $("#mail-subject").val();
  var information = $("#mail-information").val();
  $.post("contact.php",
      {
        name: name,
        lastname: lastname,
        email: email,
        phone: phone,
        subject: subject,
        information: information,
        submit: "yes"
      },
      function(data){
          $(".form-message").html( data );
      }
  );
});
</script>

contact.php:

if (isset($_POST['submit'])) {


  $email_to = "#";

  $email_subject = "#";

  $name = $_POST['name'];
  $lastname = $_POST['lastname'];
  $email = $_POST['email'];
  $phone = $_POST['phone'];
  $subject = $_POST['subject'];
  $information = $_POST['information'];


  $errorEmpty = false;
  $errorEmail = false;

  if (empty($name) || empty($email) || empty($subject) || empty($information)) {
    echo "<span class='form-error'>Voer alle velden in!</span>";
    $errorEmpty = true;
  }
  elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "<span class='form-error'>Geef een geldig E-mail!</span>";
    $errorEmail = true;
  }
  else {
    $formcontent=" Naam: $name \n\n Achternaam: $lastname \n\n Email: $email \n\n Telefoon: $phone \n\n Onderwerp: $subject \n\n Informatie: $information";
    $mailheader = "From: ".$_POST["email"]."\r\n";
    $headers = "From: ". htmlspecialchars($_POST['name']) ." <" . $_POST['email'] . ">\r\n";
    $headers .= "Reply-To: " . $_POST['email'] . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    mail($email_to, $subject, $formcontent, $mailheader);
    echo "<span class='form-success'>E-mail has been sent!</span>";
  }

}

【讨论】:

    【解决方案3】:

    这里发生了两个 javascript 事件。您有由 type="submit" 按钮触发的表单提交事件。同一个按钮触发onclick 事件。相反,您可以在表单中添加一个 Id 并列出到 onSubmit 事件,例如

    <form id="email-form">
    ...
    </form>
    
    $("#the-form").submit(function(event) {
      event.preventDefault();
      ...
    });
    

    那么您应该能够发出ajax 请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-27
      • 2023-04-06
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多