Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A very simple, yet complete, AJAX contact form for WordPress.
<?php
class ContactFormProcessing
{
protected $action = 'example_contact_form';
public function ajaxInit()
{
add_action("wp_ajax_{$this->action}", [$this, 'process']);
add_action("wp_ajax_nopriv_{$this->action}", [$this, 'process']);
}
/**
* Declare the form fields
*
* @return array
*/
public function fields()
{
return [
'name' => [
'label' => 'Name',
'type' => 'text',
],
'email' => [
'label' => 'Email address',
'type' => 'email',
],
'message' => [
'label' => 'Message',
'type' => 'textarea',
]
];
}
public function render()
{
$output = '<form class="' . $this->action . '" method="post">';
foreach ($this->fields() as $fieldId => $field) {
$value = !empty($field['default']) ? $field['default'] : '';
$output .= "<div class='form-field form-field--{$fieldId}'>";
$output .= "<label>{$field['label']}</label>";
switch ($field['type']) {
case "email":
$output .= "<input type='email' value='" . esc_attr($value) . "' name='{$fieldId}' />";
break;
case "textarea":
$output .= "<textarea name='{$fieldId}' />" . esc_textarea($value) . "</textarea>";
break;
default:
$output .= "<input type='text' value='" . esc_attr($value) . "' name='{$fieldId}' />";
break;
}
$output .= "</div>";
}
$output .= "<button type='submit'>Send message</button>";
$output .= "</form>";
return $output;
}
/**
* Process the AJAX request.
*
* @return string The JSON string.
*/
public function process()
{
// prepare a generic response.
$response = [
'_status' => 'success',
'_message' => 'Your message has been sent. Thank you.'
];
// Get the data from AJAX
if (!empty($_POST['data'])) {
// The data is sent as a URL string. Convert it to array
parse_str($_POST['data'], $data);
// Just loop over the form fields
foreach ($this->fields() as $fieldId => $field) {
// Process this individual field.
if (empty($data[$fieldId])) {
$response['_status'] = 'error';
$response['_message'] = "The `{$field['label']}` is required.";
break;// Stop the loop. We have an error.
} else {
// Save data somehow if needed.
}
}
// Send the email if all input data is OK.
if ($response['status'] == 'success') {
wp_mail(
'my_mail@example.com',
'You got a new message.',
$data['message'],
'From: ' . $data['email'] . "\r\n" . 'Reply-To: ' . $data['email'] . "\r\n"
);
}
}
// Return the response as a JSON string that can be parsed in JavaScript.
echo json_encode($response);
die();
}
}
jQuery('.example_contact_form').on('submit', function (event) {
event.preventDefault();
var data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
data: {
'action': 'example_contact_form',
'data': data
},
success: function (response) {
// console.log(response);
data = JSON.parse(response);
if(data._status === 'success'){
jQuery(':input').val(''); // Clear the form
}
alert(data._message);
},
complete: function () {
},
});
});
@awps
Copy link
Author

awps commented Dec 16, 2018

Init the contact form in functions.php:

$cf = new ContactFormProcessing();
$cf->ajaxInit();

Place this code in that place where you want to display the form(ie: to the end of a blog post).

$cf = new ContactFormProcessing();
echo $cf->render();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment