AJAX表单不显示成功或错误消息

时间:2018-01-22 22:32:33

标签: javascript php jquery html ajax

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

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>

3 个答案:

答案 0 :(得分:1)

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

尝试这样......如果有任何新问题,请编辑您的问题。

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

<强> page.html中:

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

}

<强> contact.php:

:1, :2

答案 1 :(得分: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>

发送-email.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 :(得分:0)

这里发生了两个javascript事件。您有表单提交事件,该事件由type =“submit”按钮触发。同一个按钮触发onclick事件。相反,您可以向表单添加ID并将其列为onSubmit事件,例如

<form id="email-form">
...
</form>

$("#the-form").submit(function(event) {
  event.preventDefault();
  ...
});

然后您应该能够发出ajax请求。