自定义AJAX表单不能异步工作

时间:2016-03-18 作者:Simon

我有一个联系人,他使用PHP mailer,我已经将其集成到我的Wordpress博客中。脚本发送电子邮件没问题-问题是它不能异步工作,因此一旦提交表单,我就会转到另一个页面,上面有以下文本:{"message":"Your message was successfully submitted from PHP."}. 当在wordpress之外使用时,该脚本可以正常工作-我不知道发生了什么。

HTML

<div class="col-sm-8 site-block">
        <form id="form" method="post" class="form-horizontal ajax" action="<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php" data-toggle="validator">
          <div class="form-group">
            <label for="inputName" class="col-sm-2 control-label">Name</label>
            <div class="col-sm-10">
              <input name="name" type="text" class="form-control" id="inputName" placeholder="Enter your full name and title here" required>
            </div>
          </div>
          <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Phone</label>
            <div class="col-sm-10">
              <input name="number" type="number" class="form-control" id="inputEmail3" placeholder="Enter your preferred telephone number here" required>
            </div>
          </div>
          <div class="form-group">
            <label for="inputEmail" class="col-sm-2 control-label">Email</label>
            <div class="col-sm-10">
              <input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter your preferred email address here" required>
            </div>
          </div>
          <div class="form-group">
            <label for="inputMessage" class="col-sm-2 control-label">Message</label>
            <div class="col-sm-10">
              <textarea name="description" class="form-control" id="inputMessage" placeholder="Type your message here" rows="3"></textarea>
            </div>
          </div>

          <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button id="submit-email" name="submit" type="submit" class="btn btn-danger">Submit</button>
            </div>
          </div>
        </form>
                  <div id="feedbackSubmit"></div>

      </div>

PHP

<?php

  /**
   * Sets error header and json error message response.
   *
   * @param  String $messsage error message of response
   * @return void
   */
  function errorResponse ($messsage) {
    header(\'HTTP/1.1 500 Internal Server Error\');
    die(json_encode(array(\'message\' => $messsage)));
  }
  /**
   * Pulls posted values for all fields in $fields_req array.
   * If a required field does not have a value, an error response is given.
   */
  function constructMessageBody () {
    $fields_req =  array("name" => true, "description" => true, "email" => true, "number" => true);
    $message_body = "";
    foreach ($fields_req as $name => $required) {
      $postedValue = $_POST[$name];
      if ($required && empty($postedValue)) {
        errorResponse("$name is empty.");
      } else {
        $message_body .= ucfirst($name) . ":  " . $postedValue . "\\n";
      }
    }
    return $message_body;
  }


//header(\'Content-type: application/json\');


//attempt to send email
$messageBody = constructMessageBody();
require \'php_mailer/PHPMailerAutoload.php\';
$mail = new PHPMailer;
$mail->CharSet = \'UTF-8\';

$mail->setFrom($_POST[\'email\'], $_POST[\'name\']);
$mail->addAddress("[email protected]");
$mail->Subject = $_POST[\'name\'];
$mail->Body  = $messageBody;
//try to send the message
if($mail->send()) {
  echo json_encode(array(\'message\' => \'Your message was successfully submitted from PHP.\'));
} else {
  errorResponse(\'An expected error occured while attempting to send the email: \' . $mail->ErrorInfo);
}

 ?>

jQuery

(function($) {

  $(\'#form\').on(\'submit\', function(){
    event.preventDefault();  

    var contactFormUtils = {
      clearForm: function () {
        grecaptcha.reset();
      },
      addAjaxMessage: function(msg, isError) {
        $("#feedbackSubmit").append(\'<div id="emailAlert" class="alert alert-\' + (isError ? \'danger\' : \'success\') + \'" style="margin-top: 5px;">\' + $(\'<div/>\').text(msg).html() + \'</div>\');
      }
    };


    $(\'#submit-email\').prop(\'disabled\', true).html("sending");

      var that = $(this),
        url = that.attr(\'action\'),
        type = that.attr(\'method\'),
        data = {};

      that.find(\'[name]\').each(function(index, value){
        var that = $(this),
        name = that.attr(\'name\'),
        value = that.val();
        data[name] = value;

      });

      $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(data) {
          console.log(\'success\');
          $(\'#form\').fadeOut(400)
          contactFormUtils.addAjaxMessage(data.message, false);
          contactFormUtils.clearForm();

        },
        error: function(response) {
          console.log(\'error\');
          contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
          $(\'#submit-report\').prop(\'disabled\', false).html("Send message");
          contactFormUtils.clearForm();

        },
        complete: function() {
          console.log(\'complete\');

        }
      });

    return false;
  });
})( jQuery );

1 个回复
SO网友:RRikesh

第一个可能的问题:您正在使用name 在表单中。你不应该,因为这是reserved term 在WordPress中。

第二个可能的问题:您使用的表单操作URL为<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php. 如果使用任何WordPress函数(或functions.php 和插件)。This is the correct way 在WordPress中实现AJAX。