AJAX form not displaying succes or error message

前端 未结 3 1522
忘了有多久
忘了有多久 2021-01-26 07:08

I\'ve asked this question before, but I still didn\'t figure it out. I\'ve made some changes, but I unfortunately still didn\'t get any luck. The form itself works, but it shoul

相关标签:
3条回答
  • 2021-01-26 07:16

    Here is how I would do it. I simplified the code for better understanding.

    Option 1: One file (contact.php), one form, no ajax, no onclick event:

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

    Option 2: Two files, an ajax, an onclick event, no form at all:

    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>
    

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

    Optional: Option 1 with client-side validation as well:

    You can validate the form before submission and, if at least one field is not valid (empty value, false email address, etc), you can stop the submission and display a corresponding error message instead:

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

    Of course, for option 2, you can achieve such a validation easily, by including the validation code inside the onclick handler, and not running the ajax request if the input is not valid.

    Good luck!

    0 讨论(0)
  • 2021-01-26 07:16

    That just CAN'T be in one single file. You need two.

    Try like this... And edit your question with some new issue if any.

    And notice the submit event handler... Instead of a click handler.

    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>";
      }
    
    }
    
    0 讨论(0)
  • 2021-01-26 07:27

    There are two javascript events happening here. You have the form submission event which is triggered by the button of type="submit". That same button its triggering an onclick event. Instead, you could add an Id to the form and listed to a onSubmit event such as

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

    Then you should be able to make the ajax request.

    0 讨论(0)
提交回复
热议问题