自定义AJAX表单不能正常工作

时间:2016-03-18 12:15:29

标签: javascript jquery ajax wordpress asynchronous

我有一个使用PHP邮件的联系人,我已将其整合到我的Wordpress博客中。该脚本发送电子邮件没有问题 - 问题是它不能正常工作,因此一旦提交表单,我将被带到另一个页面,其中包含以下文本:{"message":"Your message was successfully submitted from PHP."}。在wordpress之外使用时,脚本按预期工作 - 我不知道最近会发生什么。

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("example@example.com");
$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);
}

 ?>

&#13;
&#13;
 (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 );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

更改

 jQuery('#form').on('submit', function(){

 jQuery('.ajax').on('submit', function(event){

并将所有$替换为jQuery

将您的代码包装在文档就绪函数

jQuery(function(){});