如何让AJAX联系表单实际发送邮件?

时间:2015-02-03 01:28:02

标签: php jquery html ajax contact-form

我有一个联系表格,其中包含所需形式的所有必要基本功能。我排除action="",因为在使用AJAX时不需要它。当我在联系表单中输入所有必填字段时,它只是说消息已发送,但实际上没有收到任何内容。我检查了浏览器的调试器,它完全收到了输入字段的信息,但在退出ajax函数并返回false之前,它只会上升到success: function(msg) {。其他时候,它会说您的消息已成功发送,但实际上并未发送电子邮件。我做错了什么或者错过了什么?

我的网站可供参考:http://www.jaimepenzellna.com

index.html:(联系表单)

<form method="post" id="contactForm" role="form">
        <div class="col-sm-8 col-md-8">
          <div class="form-group wow bounceInUp">
            <label for="contactName">Name <span class="required">*</span></label>
            <input type="text" size="35" class="form-control" name="contactName" id="contactName" title="Please enter your name (at least 2 characters)">
          </div>
          <div class="form-group wow bounceInUp">
            <label for="contactEmail">Email <span class="required">*</span></label>
            <input type="email" size="35" class="form-control" name="contactEmail" id="contactEmail" title="Please enter a valid email address">
          </div>
          <div class="form-group wow bounceInUp">
            <label for="contactSubject">Subject</label>
            <input type="text" size="35" class="form-control" name="contactSubject" id="contactSubject">
          </div>
           <div class="form-group wow bounceInUp">
            <label for="contactMessage">Message <span class="required">*</span></label>
            <textarea name="contactMessage" class="form-control" id="contactMessage" cols="50" rows="15" title="Please enter your message (at least 10 characters)"></textarea>
           </div>
           <div class="form-group wow bounceInUp">
               <button name="submit" type="submit" class="btn btn-lg btn-primary" id="submit">Submit</button>
               <span id="image-loader">
                <img alt="" src="images/loader.gif">
               </span>
               <!-- contact-warning -->
               <div id="message-warning">Error!</div>
               <!-- contact-success -->
               <div id="message-success">
                <i class="fa fa-check"></i>Your message was sent, thank you!<br/>
               </div>
           </div>
        </div>
      </form>

(正文标记底部的脚本)

jQuery(document).ready(function($){
   $('form#contactForm button#submit').click(function() {

      $('#image-loader').fadeIn();

      var contactName = $('#contactForm #contactName').val();
      var contactEmail = $('#contactForm #contactEmail').val();
      var contactSubject = $('#contactForm #contactSubject').val();
      var contactMessage = $('#contactForm #contactMessage').val();

      var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
               '&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;

      $.ajax({

          type: "POST",
          url: "inc/sendEmail.php",
          data: data,
          success: function(msg) {

            // Message was sent
            if (msg == 'OK') {
               $('#image-loader').fadeOut();
               $('#message-warning').hide();
               $('#contactForm').fadeOut();
               $('#message-success').fadeIn();
            }
            // There was an error
            else {
               $('#image-loader').fadeOut();
               $('#message-warning').html(msg);
               $('#message-warning').fadeIn();
            }

          }

      });
      return false;
   });


});

sendMail.php:

<?php

// Replace this with your own email address
$siteOwnersEmail = 'jnp5028@rit.edu';


if($_POST) {

   $name = trim(stripslashes($_POST['contactName']));
   $email = trim(stripslashes($_POST['contactEmail']));
   $subject = trim(stripslashes($_POST['contactSubject']));
   $contact_message = trim(stripslashes($_POST['contactMessage']));

   // Check Name
    if (strlen($name) < 2) {
        $error['name'] = "Please enter your name.";
    }
    // Check Email
    if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
        $error['email'] = "Please enter a valid email address.";
    }
    // Check Message
    if (strlen($contact_message) < 15) {
        $error['message'] = "Please enter your message. It should have at least 15 characters.";
    }
   // Subject
    if ($subject == '') { $subject = "Contact Form Submission"; }


   // Set Message
   $message .= "Email from: " . $name . "<br />";
   $message .= "Email address: " . $email . "<br />";
   $message .= "Message: <br />";
   $message .= $contact_message;
   $message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";

   // Set From: header
   $from =  $name . " <" . $email . ">";

   // Email Headers
    $headers = "From: " . $from . "\r\n";
    $headers .= "Reply-To: ". $email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";


   if (!$error) {

      ini_set("sendmail_from", $siteOwnersEmail); // for windows server
      $mail = mail($siteOwnersEmail, $subject, $message, $headers);

        if ($mail) { echo "OK"; }
      else { echo "Something went wrong. Please try again."; }

    } # end if - no validation error

    else {

        $response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
        $response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
        $response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;

        echo $response;

    } # end if - there was a validation error

}

?>

1 个答案:

答案 0 :(得分:0)

我知道调试联系表单的最佳方式如下:

将以下内容添加到php文件的顶部:

error_reporting(-1);` 
ini_set('display_errors', 'On');

然后创建一个html页面,其中只包含联系表单的简单骨骼,如下所示。请注意在表单上添加action="sendEmail.php"并根据需要设置路径:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" id="contactForm" role="form" action="sendEmail.php">
 Name: <input type="text" size="35" class="form-control" name="contactName" id="contactName" title="Please enter your name (at least 2 characters)"><br>
 Email: <input type="email" size="35" class="form-control" name="contactEmail" id="contactEmail" title="Please enter a valid email address"><br>
 Subject: <input type="text" size="35" class="form-control" name="contactSubject" id="contactSubject"><br>
 Body: <textarea name="contactMessage" class="form-control" id="contactMessage" cols="50" rows="15" title="Please enter your message (at least 10 characters)"></textarea><br>
  <button name="submit" type="submit" class="btn btn-lg btn-primary" id="submit">Submit</button>
</form>
</body>
</html>

将文件上传到服务器,然后使用表单直接发布到php页面。这将显示屏幕右侧php文件中生成的任何错误。

这样做我们就会发现错误:

Notice: Undefined variable: message in /home/content/08/10125908/html/sendEmail.php on line 39

这告诉我们,在第39行,我们尝试使用一个名为“message”的变量,但没有这样的变量可用。

这是因为这一行$message .= "Email from: " . $name . "<br />";,特别是这部分$message .=说“取字符串变量$message并将以下内容添加到其中”但是$message是未定义,因此错误。

我们可以通过在$message

之前将$message ='';声明为空字符串来解决此问题

修复并再次尝试,我们收到一个新错误:

Notice: Undefined variable: error in /home/content/08/10125908/html/sendEmail.php on line 56

这告诉我们,在第56行,我们尝试使用一个名为“error”的变量,但没有这样的变量可用。

这是因为我们只在if语句中声明$error如果有错误,如果没有错误,它永远不会被设置,因此在我们尝试使用它时是未定义的。

我们可以通过声明error使用$error = array()之类的名称和主题来解决这个问题,或者使用if (isset($error))检查变量是否已声明(我更喜欢后者)但请注意,这会颠倒if子句,失败代码需要先成功代码,你可以做if (!isset($error)),但逻辑很难遵循)

解决这两个错误,你们都已经完成了! Working example

所以,固定的php文件看起来像是:

    <?php

// the next two lines will turn on error reporting for the page
// uncomment them to see warnings
// error_reporting(-1); 
// ini_set('display_errors', 'On'); 
// these are really only useful if you actually go to the page 
// you wont see the warnings if you call the page with ajax


// Replace this with your own email address
$siteOwnersEmail = 'jnp5028@rit.edu';


if($_POST) {

   $name = trim(stripslashes($_POST['contactName']));
   $email = trim(stripslashes($_POST['contactEmail']));
   $subject = trim(stripslashes($_POST['contactSubject']));
   $contact_message = trim(stripslashes($_POST['contactMessage']));
   // Check Name
    if (strlen($name) < 2) {
        $error['name'] = "Please enter your name.";
    }
    // Check Email
    if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
        $error['email'] = "Please enter a valid email address.";
    }
    // Check Message
    if (strlen($contact_message) < 15) {
        $error['message'] = "Please enter your message. It should have at least 15 characters.";
    }
   // Subject
    if ($subject == '') { $subject = "Contact Form Submission"; }


   // Set Message
   $message =''; // you need to define  `$message` as an empty string, otherwise when the `$message .=` on the next line tries to use it, it is undefined
   $message .= "Email from: " . $name . "<br />";
   $message .= "Email address: " . $email . "<br />";
   $message .= "Message: <br />";
   $message .= $contact_message;
   $message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";

   // Set From: header
   $from =  $name . " <" . $email . ">";

   // Email Headers
    $headers = "From: " . $from . "\r\n";
    $headers .= "Reply-To: ". $email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";


   if (isset($error)) {

        $response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
        $response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
        $response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;

        echo $response;


    } # end if - there was a validation error
    else {


      ini_set("sendmail_from", $siteOwnersEmail); // for windows server
      $mail = mail($siteOwnersEmail, $subject, $message, $headers);

        if ($mail) { echo "OK"; }
      else { echo "Something went wrong. Please try again."; }

    } # end if - no validation error

}

?>