Search code examples
javascriptphphtmljqueryajax

Why won't my AJAX Contact Form stay on the same page?


I have a contact form on my site that I originally set up over 5 years ago. I remember that it used to display error/success messages directly on the page in the #form-messages div, but now it changes the page to send.php with the unformatted text displayed instead of staying on the contact form page and outputting it there, and I can't for the life of me figure out why. Shouldn't the event.preventDefault(); prevent the default behavior of changing the page?

Here's the relevant HTML:

<form id="ajax-contact" method="post" action="send.php">
    <div class="field">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" autocomplete="name" required>
    </div>

    <div class="field">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" autocomplete="email" required>
    </div>

    <div class="field">
        <label for="message">Message</label>
        <textarea id="message" name="message" required></textarea>
    </div>
    <div class="field">
        <button type="submit" class="button g-recaptcha" data-sitekey="X" data-callback='onSubmit' data-action='submit'>Send</button>
    </div>
</form>
<div id="form-messages"></div>

Here's the contact.js:

$(function() {
    // Get the form.
    var form = $('#ajax-contact');

    // Get the messages div.
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    form.submit(function(event) {
        // Stop the browser from submitting the form.
        event.preventDefault();

        // Serialize the form data.
        var formData = form.serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: formData,
            captcha: grecaptcha.getResponse()

        }).done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            formMessages.removeClass('error');
            formMessages.addClass('success');

            // Set the message text.
            if (data.responseText !== '') {
                formMessages.text(data.responseText);
            } else {
                formMessages.text('Oops! An error occurred and your message could not be sent.');
            }

            // Clear the form.
            $('#name').val('');
            $('#email').val('');
            $('#message').val('');
        }).fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            formMessages.removeClass('success');
            formMessages.addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                formMessages.text(data.responseText);
            } else {
                formMessages.text('Oops! An error occurred and your message could not be sent.');
            }
        });
    });
});

And here's the send.php:

<?php
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // If the Google Recaptcha box was clicked
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=X&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
        $obj = json_decode($response);

        // If the Google Recaptcha check was successful
        if($obj->success == true) {
          // Clean up the data
          $name = strip_tags(trim($_POST["name"]));
          $name = str_replace(array("\r","\n"),array(" "," "),$name);
          $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
          $message = trim($_POST["message"]);

          // Check for empty fields
          if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
          }

          // Set up the email to me
          $email_sender = "[email protected]";
          $email_receiver = "[email protected]";
          $subject = "New message from $name";
          $email_content = "Name: $name\nEmail: $email\n\nMessage:\n$message\n";
          $email_headers = "From: $name <$email_sender>" . "\r\n" . "Reply-To: $name <$email>";

          // Set up the confirmation email
          $confirm_content =  "Hi $name,\n\nI'll get back to you as soon as I can. For your convenience, here is a copy of the message you sent:\n\n----------\n\n$message\n";
          $confirm_headers = "From: My Name <$email_sender>"  . "\r\n" . "Reply-To: My Name <$email_receiver>";

          // Send the email to me
          if (mail($email_receiver, $subject, $email_content, $email_headers)) {
            http_response_code(200);
            echo "Thank You! Your message has been sent, and you should have received a confirmation email. I'll get back to you as soon as I can!";
            // Send the confirmation email
            mail($email, "Thank you for your message!", $confirm_content, $confirm_headers);
          } 
          // If the server was unable to send the mail
          else {
            http_response_code(500);
            echo "Oops! Something went wrong, and we couldn't send your message. Please try again.";
          }
      } 
      // If the Google Recaptcha check was not successful    
      else {
        http_response_code(400);
        echo "Robot verification failed. Please try again.";
      }
  } 
  // If the Google Recaptcha box was not clicked   
  else {
    http_response_code(400);
    echo "Please click the reCAPTCHA box.";
  }      
} 
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.         
else {
  http_response_code(403);
  echo "There was a problem with your submission, please try again.";
}      
?>

Solution

  • The issue appears to be in the captcha implementation. I originally followed Google's own recommendation to bind the challenge to the submit button, which seems to have prevented me from preventing the default behavior of that button. I eventually gave up on trying to use the invisible reCAPTCHA and went back to the checkbox implementation, and I finally got it to work.

    My send.php is unchanged.

    The main change I made in the HTML is that the captcha is now attached to an empty div instead of to the submit button:

    <form id="ajax-contact" method="post" action="send.php">
        <div class="field">
            <label for="name">Name</label>
            <input type="text" id="name" name="name" autocomplete="name" required>
        </div>
    
        <div class="field">
            <label for="email">Email</label>
            <input type="email" id="email" name="email" autocomplete="email" required>
        </div>
    
        <div class="field">
            <label for="message">Message</label>
            <textarea id="message" name="message" required></textarea>
        </div>
    
        <div id="recaptcha" class="g-recaptcha" data-sitekey="x"></div>
    
        <div id="form-messages"></div>
    
        <div class="field">
            <button id="contact-submit" type="submit" class="button">Send</button>
        </div>
    </form>
    

    My contact.js is almost completely unchanged, except for the way I set the message text in the .done section:

    $(function() {
        var form = $('#ajax-contact');
        var formMessages = $('#form-messages');
    
        // Set up an event listener for the contact form.
        form.submit(function(event) {
            // Stop the default behavior from submitting the form.
            event.preventDefault();
    
            // Serialize the form data.
            var formData = form.serialize();
    
            // Submit the form using AJAX.
            $.ajax({
                type: 'POST',
                url: form.attr('action'),
                data: formData,
                captcha: grecaptcha.getResponse()
            }).done(function(response) {
                // Make sure that the formMessages div has the 'success' class.
                formMessages.removeClass('error');
                formMessages.addClass('success');
    
                // Set the message text.
                formMessages.text(response);
    
                // Clear the form.
                $('#name').val('');
                $('#email').val('');
                $('#message').val('');
            }).fail(function(data) {
                // Make sure that the formMessages div has the 'error' class.
                formMessages.removeClass('success');
                formMessages.addClass('error');
    
                // Set the message text.
                if (data.responseText !== '') {
                    formMessages.text(data.responseText);
                } else {
                    formMessages.text('Oops! An error occurred and your message could not be sent.');
                }
            });
        });
    });