0

I have a contact from that uses PHP mailer that I have integrated into my Wordpress blog. The script sends emails no problem - the issue is that it does not work async so once the form is submitted I am taken to another page with the following text on it: {"message":"Your message was successfully submitted from PHP."}. The script works as expected when used outside of wordpress - I have no idea whats going on.

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("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);
}

 ?>

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

First probable issue: You're using name in the form. You should not, since it's a reserved term in WordPress.

Second probable issue: You're using a form action URL of <?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php. That will break if you use any WordPress functions (or functions defined in functions.php and plugins). This is the correct way to implement AJAX in WordPress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.