Создание и продвижение продающих сайтов

+380 (66) 41-71-976

How to Create a WordPress AJAX Contact Form 20.02.2019(, , )

Write the Form HTML

<form id="contact-form">
  <input type="hidden" name="action" value="contact_send" />
  <input type="text" name="name" placeholder="Your name..." />
  <input type="email" name="email" placeholder="Your email..." />
  <textarea name="message" placeholder="Your message..."></textarea>
  <input type="submit" value="Send Message" />
</form>

Take note of the hidden action form input. That value ties in directly to the functions.php AJAX handler we’ll write soon.

Write a jQuery $.ajax Submit Event Handler

<script type="text/javascript">
  jQuery(document).ready(function ($) {
    var is_sending = false,
        failure_message = 'Whoops, looks like there was a problem. Please try again later.';
 
    $('#contact-form').submit(function (e) {
      if (is_sending || !validateInputs()) {
        return false; // Don't let someone submit the form while it is in-progress...
      }
      e.preventDefault(); // Prevent the default form submit
      var $this = $(this); // Cache this
      $.ajax({
        url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
        type: 'post',
        dataType: 'JSON', // Set this so we don't need to decode the response...
        data: $this.serialize(), // One-liner form data prep...
        beforeSend: function () {
          is_sending = true;
          // You could do an animation here...
        },
        error: handleFormError,
        success: function (data) {
          if (data.status === 'success') {
            // Here, you could trigger a success message
          } else {
            handleFormError(); // If we don't get the expected response, it's an error...
          }
        }
      });
    });
 
    function handleFormError () {
      is_sending = false; // Reset the is_sending var so they can try again...
      alert(failure_message);
    }
 
    function validateInputs () {
      var $name = $('#contact-form > input[name="name"]').val(),
          $email = $('#contact-form > input[name="email"]').val(),
          $message = $('#contact-form > textarea').val();
      if (!$name || !$email || !$message) {
        alert('Before sending, please make sure to provide your name, email, and message.');
        return false;
      }
      return true;
    }
  });
</script>

Write the WP AJAX Controller Actions

Now, let’s write the back-end piece that will communicate with the AJAX. Nothing too special here. Just some basic validation, and making use of wp_mail

function sendContactFormToSiteAdmin () {
  try {
    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
      throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.');
    }
    if (!is_email($_POST['email'])) {
      throw new Exception('Email address not formatted correctly.');
    }
 
    $subject = 'Contact Form: '.$reason.' - '.$_POST['name'];
    $headers = 'From: My Blog Contact Form <contact@myblog.com>';
    $send_to = "my@contactemail.com";
    $subject = "MyBlog Contact Form ($reason): ".$_POST['name'];
    $message = "Message from ".$_POST['name'].": \n\n ". $_POST['message'] . " \n\n Reply to: " . $_POST['email'];
 
    if (wp_mail($send_to, $subject, $message, $headers)) {
      echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.'));
      exit;
    } else {
      throw new Exception('Failed to send email. Check AJAX handler.');
    }
  } catch (Exception $e) {
    echo json_encode(array('status' => 'error', 'message' => $e->getMessage()));
    exit;
  }
}
add_action("wp_ajax_contact_send", "sendContactFormToSiteAdmin");
add_action("wp_ajax_nopriv_contact_send", "sendContactFormToSiteAdmin");