Contact Form AJAX Handler – Code Snippet

๐Ÿ“ง Complete Contact Form Email Integration Code

Add this code to enable actual email sending from the contact form.

Step 1: Add PHP Handler

Add this to your theme’s functions.php or use the Code Snippets plugin:

<?php
/**
 * Contact Form Email Handler
 * Processes submissions from Material Design contact form
 */

// Handle AJAX form submission
add_action('wp_ajax_submit_contact_form', 'handle_material_contact_form');
add_action('wp_ajax_nopriv_submit_contact_form', 'handle_material_contact_form');

function handle_material_contact_form() {
    // Verify nonce for security
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'contact_form_nonce')) {
        wp_send_json_error('Security verification failed');
        wp_die();
    }
    
    // Sanitize all inputs
    $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
    $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '';
    $subject = isset($_POST['subject']) ? sanitize_text_field($_POST['subject']) : '';
    $message = isset($_POST['message']) ? sanitize_textarea_field($_POST['message']) : '';
    
    // Validate required fields
    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        wp_send_json_error('Please fill in all required fields');
        wp_die();
    }
    
    // Validate email
    if (!is_email($email)) {
        wp_send_json_error('Please provide a valid email address');
        wp_die();
    }
    
    // Prepare email content
    $to = 'info@adinsightia.com';
    $email_subject = '[AdInsightia Contact] ' . $subject;
    
    // Build email body
    $email_body = "New contact form submission from AdInsightia website\n\n";
    $email_body .= "Name: " . $name . "\n";
    $email_body .= "Email: " . $email . "\n";
    $email_body .= "Phone: " . ($phone ? $phone : 'Not provided') . "\n";
    $email_body .= "Subject: " . $subject . "\n\n";
    $email_body .= "Message:\n" . $message . "\n\n";
    $email_body .= "---\n";
    $email_body .= "Sent from: " . get_site_url() . "\n";
    $email_body .= "Date: " . current_time('mysql') . "\n";
    $email_body .= "IP Address: " . $_SERVER['REMOTE_ADDR'];
    
    // Set email headers
    $headers = array(
        'Content-Type: text/plain; charset=UTF-8',
        'From: AdInsightia Contact Form ',
        'Reply-To: ' . $name . ' <' . $email . '>'
    );
    
    // Send email
    $sent = wp_mail($to, $email_subject, $email_body, $headers);
    
    // Also send confirmation to user
    if ($sent) {
        $user_subject = 'Thank you for contacting AdInsightia';
        $user_body = "Dear " . $name . ",\n\n";
        $user_body .= "Thank you for reaching out to us. We have received your message and will get back to you as soon as possible.\n\n";
        $user_body .= "Your message:\n" . $message . "\n\n";
        $user_body .= "Best regards,\nThe AdInsightia Team\n\n";
        $user_body .= "---\n";
        $user_body .= "This is an automated confirmation. Please do not reply to this email.";
        
        $user_headers = array(
            'Content-Type: text/plain; charset=UTF-8',
            'From: AdInsightia '
        );
        
        wp_mail($email, $user_subject, $user_body, $user_headers);
    }
    
    // Log submission (optional)
    error_log('Contact form submission from: ' . $email);
    
    // Return response
    if ($sent) {
        wp_send_json_success([
            'message' => 'Thank you! Your message has been sent successfully. We\'ll get back to you soon.'
        ]);
    } else {
        wp_send_json_error('Failed to send email. Please try again or contact us directly at info@adinsightia.com');
    }
    
    wp_die();
}

// Add nonce and AJAX URL to contact page
add_action('wp_footer', 'add_contact_form_scripts');
function add_contact_form_scripts() {
    if (is_page('contact-us')) {
        ?>
        
        

Step 2: Update Contact Form JavaScript

Update the contact form submission handler. Replace the existing script on the Contact Us page with:

<script>
document.getElementById('contactForm').addEventListener('submit', function(e) {
  e.preventDefault();
  
  // Get form data
  const formData = new FormData(this);
  const data = {
    action: 'submit_contact_form',
    nonce: contactFormNonce,
    name: formData.get('name'),
    email: formData.get('email'),
    phone: formData.get('phone'),
    subject: formData.get('subject'),
    message: formData.get('message')
  };
  
  // Disable submit button
  const submitBtn = this.querySelector('button[type="submit"]');
  const originalText = submitBtn.innerHTML;
  submitBtn.disabled = true;
  submitBtn.innerHTML = 'hourglass_empty Sending...';
  
  // Send AJAX request
  fetch(ajaxUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams(data)
  })
  .then(response => response.json())
  .then(result => {
    const snackbar = document.getElementById('snackbar');
    
    if (result.success) {
      // Success
      snackbar.textContent = result.data.message;
      snackbar.style.background = '#4caf50';
      snackbar.classList.add('show');
      
      // Reset form
      document.getElementById('contactForm').reset();
    } else {
      // Error
      snackbar.textContent = result.data || 'An error occurred. Please try again.';
      snackbar.style.background = '#f44336';
      snackbar.classList.add('show');
    }
    
    // Re-enable submit button
    submitBtn.disabled = false;
    submitBtn.innerHTML = originalText;
    
    // Hide snackbar after 5 seconds
    setTimeout(() => {
      snackbar.classList.remove('show');
    }, 5000);
  })
  .catch(error => {
    console.error('Error:', error);
    const snackbar = document.getElementById('snackbar');
    snackbar.textContent = 'Network error. Please check your connection and try again.';
    snackbar.style.background = '#f44336';
    snackbar.classList.add('show');
    
    submitBtn.disabled = false;
    submitBtn.innerHTML = originalText;
    
    setTimeout(() => {
      snackbar.classList.remove('show');
    }, 5000);
  });
});

Installation Instructions

Method 1: Using Code Snippets Plugin (Recommended)

  1. Install and activate “Code Snippets” plugin
  2. Go to: Snippets โ†’ Add New
  3. Title: “Contact Form Email Handler”
  4. Paste the PHP code from Step 1
  5. Set to run everywhere
  6. Save and Activate

Method 2: Add to functions.php

  1. Go to: Appearance โ†’ Theme File Editor
  2. Select functions.php
  3. Scroll to the bottom
  4. Paste the PHP code from Step 1
  5. Click Update File

Update Contact Page

  1. Go to: Pages โ†’ All Pages
  2. Edit “Contact Us” page
  3. Find the existing <script> section at the bottom
  4. Replace it with the code from Step 2
  5. Click Update

Testing

  1. Make sure WP Mail SMTP is configured
  2. Visit your Contact Us page
  3. Fill out the form
  4. Click “Send Message”
  5. Check info@adinsightia.com for the email
  6. Check the sender’s email for confirmation

Troubleshooting

  • No email received: Check WP Mail SMTP settings and test email
  • JavaScript errors: Check browser console for errors
  • Security error: Clear cache and try again
  • Form not submitting: Make sure both scripts are added correctly

Features Included

  • โœ… Sends email to info@adinsightia.com
  • โœ… Sends confirmation email to sender
  • โœ… Input validation and sanitization
  • โœ… Security nonce verification
  • โœ… Loading state on submit button
  • โœ… Success/error notifications
  • โœ… Form reset after successful submission
  • โœ… IP address and timestamp logging
  • โœ… Professional email formatting

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *