简体   繁体   中英

Ajax & PHP Contact Form displays a blank page when clicking “submit”

I'm trying to use this contact form on an HTML template/theme but when I click on the "submit" button, it redirects me to a blank/white page (with an empty source code; and the address bar shows that it's the mail.php page) whether I've validly completed the name, email, message fields or not. If I did validly complete those three fields, then it successfully sends the email but it still redirects to the blank page, and if I didn't it just redirects to the blank mail.php page without showing any php/validation errors.

I tested this both on localhost (xampp) and on my live server with the same result.

contact.html (jQuery - inside the header of the page):

<script >
    $("#contactform").submit(function(e){
      e.preventDefault();
      var name = $("#name").val();
      var email = $("#email").val();
      var message = $("#message").val();
      var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
      function isValidEmail(emailAddress) {
        var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
        return pattern.test(emailAddress);
      };

      if (isValidEmail(email) && (message.length > 10) && (name.length > 1)){
        $.ajax({
        type: "POST",
        url: "mail.php",
        data: dataString,
        success: function(){
          $('.success').fadeIn(1000);
        }
        });
      } else{
        $('.error').fadeIn(1000);
      }

      return false;
    });
</script>

contact.html (contact form):

<form id="contactform" action="mail.php" method="post">
    <table>
        <tr>
            <td><input type="text" id="name" name="name" placeholder="Your Name" /></td>
        </tr>
        <tr>
            <td><input type="text" id="email" name="email" placeholder="Your Email Address" /></td>
        </tr>
        <tr>
            <td><textarea id="message" placeholder="Your Message" name="message" rows="10" cols="20"></textarea></td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="Send" id="send" class="button" />
                <input type="reset" value="Reset" class="button" />
            </td>
        </tr>
    </table>
    <p class="success" style="display:none">Your message has been sent successfully.</p>
        <p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</form>

mail.php :

<?php
error_reporting( E_ALL );
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {

  // detect & prevent header injections
  $test = "/(content-type|bcc:|cc:|to:)/i";
  foreach ( $_POST as $key => $val ) {
    if ( preg_match( $test, $val ) ) {
      exit;
    }
  }

  //send email
  mail( "johndoe@gmail.com", "Contact Form: ".$_POST['name'], $_POST['message'], "From:" . $_POST['email'] );

}
?>

Your action in the form should not be mail.php. Because of this the form is submitted before the AJAX request could be handled.

Just remove the form action and do it on same page coz its submitting via ajax

<form id="contactform" method="post">
<table>
    <tr>
        <td><input type="text" id="name" name="name" placeholder="Your Name" /></td>
    </tr>
    <tr>
        <td><input type="text" id="email" name="email" placeholder="Your Email Address" /></td>
    </tr>
    <tr>
        <td><textarea id="message" placeholder="Your Message" name="message" rows="10" cols="20"></textarea></td>
    </tr>
    <tr>
        <td>
            <input type="submit" value="Send" id="send" class="button" />
            <input type="reset" value="Reset" class="button" />
        </td>
    </tr>
</table>
<p class="success" style="display:none">Your message has been sent successfully.</p>
    <p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>

on the next you should add this

<?php if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {

// detect & prevent header injections
 $test = "/(content-type|bcc:|cc:|to:)/i";
   foreach ( $_POST as $key => $val ) {
     if ( preg_match( $test, $val ) ) {
     exit;
    }
  }

 //send email
   mail( "johndoe@gmail.com", "Contact Form: ".$_POST['name'], $_POST['message'], "From:" . $_POST['email'] );

}

I knew I must have made a silly mistake... :)) After removing the "mail.php" action from the contact form and after moving the jQuery part inside the body tag, I somehow changed the recipient email address to johndoe@gmail.com instead of my real email account. After correcting that everything started to work. Thanks Sudhanshu and Stefan.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM