Skip to content

Instantly share code, notes, and snippets.

@nikola-wd
Created December 17, 2018 02:05
Show Gist options
  • Save nikola-wd/5062a551f599c47ed44d3b03f3dbd7e5 to your computer and use it in GitHub Desktop.
Save nikola-wd/5062a551f599c47ed44d3b03f3dbd7e5 to your computer and use it in GitHub Desktop.
Wordpress custom AJAX contact form (not working)
// Helper serialize function
function serialize(form) {
var field, s = [];
if (typeof form == 'object' && form.nodeName == "FORM") {
var len = form.elements.length;
for (let i=0; i<len; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type == 'select-multiple') {
for (let j=form.elements[i].options.length-1; j>=0; j--) {
if(field.options[j].selected)
s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.options[j].value);
}
} else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value);
}
}
}
}
return s.join('&').replace(/%20/g, '+');
} // end serialize fn
const contactForm = (function() {
const $form = document.querySelector('.contact_form');
$form.addEventListener('submit', (e) => {
e.preventDefault();
const formData = serialize($form);
// console.log('formData', formData);
fetch('//localhost/webredone/wp-admin/admin-ajax.php', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(
{
'action': 'contact_form',
'data': formData
}
)
})
.then(res => res.json())
.then((res) => {
console.log(res);
if (res._status === 'success'){
// TODO: clear form fields here
}
alert(res._message);
})
.catch(err => console.log(err));
}); // event
}());
export default contactForm;
<section class="sec-contact sec-contact--1 bg-silver" id="contact-us">
<div class="container">
<h2 class="sec-title sec-title--with-lead">Contact Us</h2>
<p class="lead text-center">
Feeling ready to kickoff a project with us or still have a couple of questions. Reach out via form.
</p>
<?php
$cf = new ContactFormProcessing();
echo $cf->render();
?>
</div>
<img src="<?php echo get_template_directory_uri(); ?>/img/dots.png" class="contact-dots">
<img src="<?php echo get_template_directory_uri(); ?>/img/dots.png" class="contact-dots-2">
</section>
<?php
class ContactFormProcessing
{
protected $action = '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' placeholder='Email' value='" . esc_attr($value) . "' name='{$fieldId}' />";
break;
case "textarea":
$output .= "<textarea placeholder='Message' name='{$fieldId}' />" . esc_textarea($value) . "</textarea>";
break;
default:
$output .= "<input type='text' placeholder='Name' value='" . esc_attr($value) . "' name='{$fieldId}' />";
break;
}
// $output .= "</div>";
}
$output .= "<button type='submit' class='btn btn--sec'>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 {
// TODO: Maybe save to custom post type here
// Save data somehow if needed.
}
}
// Send the email if all input data is OK.
if ($response['status'] == 'success') {
wp_mail(
'ouroborus357@gmail.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();
}
}
<?php
/**
* underscores gbs functions and definitions
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
* @package ugwps
*/
// Comment out what is not used
// contact form processing
require get_template_directory() . '/inc/ContactFormProcessing.php';
$cf = new ContactFormProcessing();
$cf->ajaxInit();
require get_template_directory() . '/inc/nav-walker.php';
require get_template_directory() . '/inc/theme-support.php';
require get_template_directory() . '/inc/sidebars.php';
require get_template_directory() . '/inc/enqueues.php';
require get_template_directory() . '/inc/custom-post-types.php';
require get_template_directory() . '/inc/template-tags.php';
require get_template_directory() . '/inc/template-functions.php';
require get_template_directory() . '/inc/remove-css-js-version.php';
require get_template_directory() . '/inc/remove-emojis.php';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment