Contact form PHPMailer sending button is stuck loading

时间:2016-07-11 19:17:26

标签: javascript php html phpmailer contact-form

I'm having trouble with my contact form. I'm using the code from jon bake. However I can't get it to work, it's not sending the mail (or I'm not receiving it) and I don't even get the "success" message after pressing 'send'. This is how it looks in the 'console'. I also get

HTTP500 : Server Error - Failed to execute request because the server encountered an unexpected condition . ( XHR ) : POST - from console.

HTML

    <form role="form" id="feedbackForm" method = "post" data-toggle="validator" data-disable="false">
        <div class="form-group">
          <label class="control-label" for="name">Name *</label>
          <div class="input-group">
            <input type="text" class="form-control" id="name" name="name" placeholder="Enter your name" required/>
            <span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
          </div>
          <span class="help-block" style="display: none;">Please enter your name.</span>
        </div>

        <div class="form-group">
          <label class="control-label" for="phone">Phone</label>
          <input type="tel" class="form-control optional" id="phone" name="phone" placeholder="Enter your phone (Optional)"/>
          <span class="help-block" style="display: none;">Please enter a valid phone number.</span>
        </div>

        <div class="form-group">

          <span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
        </div>
        <div class="form-group">
          <label class="control-label" for="email">Email Address *</label>
          <div class="input-group">
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter your email" required/>
            <span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
          </div>
          <span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
        </div>
        <div class="form-group">
          <label class="control-label" for="message">Message *</label>
          <div class="input-group">
            <textarea rows="5" cols="30" class="form-control" id="message" name="message" placeholder="Enter your message" required></textarea>
            <span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
          </div>
          <span class="help-block" style="display: none;">Please enter a message.</span>
        </div>
        <div class="form-group">
          <div class="g-recaptcha" data-sitekey="6LfIxCQTAAAAAK7ZBb9liJNpaebx12UbmOfiqtl9"></div>
          <span class="help-block" style="display: none;">Please check that you are not a robot.</span>
        </div>
        <span class="help-block" style="display: none;">Please enter a the security code.</span>
        <button type="submit" id="feedbackSubmit" class="btn btn-primary btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback</button>
      </form>
    </div><!--/span-->
  </div><!--/row-->
  <hr>
</div><!--/.container-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="assets/vender/intl-tel-input/js/intlTelInput.min.js"></script>
<script src="assets/js/contact-form.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>

The contact-form.js

(function () {
  //using regular expressions, validate email
  var contactFormUtils = {
    isValidEmail: function (email) {
      var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]      {2,4})+$/;
  return regex.test(email);
},
//if no form errors, remove or hide error messages
clearErrors: function () {
  $('#emailAlert').remove();
  $('#feedbackForm .help-block').hide();
  $('#feedbackForm .form-group').removeClass('has-error');
},
//upon form clear remove the checked class and replace with unchecked class. Also reset Google ReCaptcha
clearForm: function () {
  $('#feedbackForm .glyphicon').removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
  $('#feedbackForm input,textarea').val("");
  grecaptcha.reset();
},
//when error, show error messages and track that error exists
addError: function ($input) {
  var parentFormGroup = $input.parents('.form-group');
  parentFormGroup.children('.help-block').show();
  parentFormGroup.addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
  $("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
    }
  };

  $(document).ready(function() {
    if ($("#phone").intlTelInput) {
      $("#phone").intlTelInput({validationScript: "assets/vender/intl-tel-    input/js/isValidNumber.js"});
      $(".intl-tel-input.inside").css('width', '100%');
    }

$("#feedbackSubmit").click(function() {
  var $btn = $(this);
  $btn.button('loading');
  contactFormUtils.clearErrors();

  //do a little client-side validation -- check that each field has a value and e-mail field is in proper format
  //use bootstrap validator (https://github.com/1000hz/bootstrap-validator) if provided, otherwise a bit of custom validation
  var $form = $("#feedbackForm"),
    hasErrors = false;
  if ($form.validator) {
    hasErrors =  $form.validator('validate').hasErrors;
  } else {
    $('#feedbackForm input,#feedbackForm textarea').not('.optional').each(function() {
      var $this = $(this);
      if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
        hasErrors = true;
        contactFormUtils.addError($(this));
      }
    });
    var $email = $('#email');
    if (!contactFormUtils.isValidEmail($email.val())) {
      hasErrors = true;
      contactFormUtils.addError($email);
    }
    var $phone = $('#phone');
    if ($phone.val() && $phone.intlTelInput && !$phone.intlTelInput("isValidNumber")) {
      hasErrors = true;
      contactFormUtils.addError($phone.parent());
    }
  }
  //if there are any errors return without sending e-mail
  if (hasErrors) {
    $btn.button('reset');
    return false;
  }
 //send the feedback e-mail
  $.ajax({
    type: "post",
    url: "../../library/sendmail.php",
    data: $form.serialize(),
    success: function(data) {
      contactFormUtils.addAjaxMessage(data.message, false);
      contactFormUtils.clearForm();
    },
    error: function(response) {
      contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
    },
    complete: function() {
      $btn.button('reset');
    }
 });
  return false;

});
$('#feedbackForm input, #feedbackForm textarea').change(function () {
  var checkBox = $(this).siblings('span.input-group-addon').children('.glyphicon');
  if ($(this).val()) {
    checkBox.removeClass('glyphicon-unchecked').addClass('glyphicon-check').css({color: 'green'});
  } else {
    checkBox.removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
  }
});
  });
})();

And the 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, "email" => true, "message" => 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');
  //do Captcha check, make sure the submitter is not a robot:)...
  $url = 'https://www.google.com/recaptcha/api/siteverify';
  $opts = array('http' =>
    array(
      'method'  => 'POST',
      'header'  => 'Content-type: application/x-www-form-urlencoded',
      'content' => http_build_query(array('secret'     => '6LfIxCQTAAAAABhWEJuLVdzE9m_-cwbBs9lM1xVi', 'response' => $_POST["g-recaptcha-response"]))
    )
  );
  $context  = stream_context_create($opts);
  $result = json_decode(file_get_contents($url, false, $context, -1, 40000));

  if (!$result->success) {
    errorResponse('reCAPTCHA checked failed!');
  }

  //attempt to send email
  $messageBody = constructMessageBody();
  require_once './vender/php_mailer/PHPMailerAutoload.php';
  include_once './vender/php_mailer/class.phpmailer.php';
  $mail = new PHPMailer;
  $mail->isSMTP();
  $mail->SMTPAuth = true;
  $mail->SMTPDebug = 2
  $mail->SMTPSecure = 'tls';
  $mail->Host = "smtp.gmail.com";
  $mail->Port = 587;
  $mail->Username = "gmail.com";
  $mail->Password = "password";

  $mail->setFrom($_POST['email'], $_POST['name']);
  $mail->addAddress "gmail.com";
  $mail->Subject = "Contact Form";
  $mail->Body  = $message_body;


  //try to send the message
  if($mail->send()) {
    echo json_encode(array('message' => 'Your message was successfully     submitted.'));
  } else {
    errorResponse('An expected error occured while attempting to send the     email: ' . $mail->ErrorInfo);
  } 
?>

I'm very new to JavaScript and PHP so maybe I've missed something but I've tried to find a solution on Google but not been able to find one.

I hope I've made myself clear, thanks.

0 个答案:

没有答案