Snippet

Enable AJAX Handling in WordPress Forms for Smooth Submissions

How to enable ajax in wordpress formWordpress ajax form submission tutorialEnable ajax for form submissions in wordpressWordpress ajax form handling guideAjax form submission wordpress pluginWordpress ajax form setupHow to use ajax in wordpress formsWordpress form ajax integrationAjax form submission wordpress exampleWordpress ajax form submission step by step

Explanation

To enable AJAX in your WordPress form, you'll need to do a few things to make it work smoothly without reloading the page.

Scripts and Security:

  • First, make sure jQuery and your custom JavaScript file are loaded. This is done using wp_enqueue_script.
  • You'll also pass some important data to your script, like the AJAX URL and a security nonce, using wp_localize_script.

Handling Form Submission:

  • When the form is submitted, the JavaScript captures the data and sends it to the server using AJAX.
  • On the server side, you check the security nonce to ensure the request is legitimate.
  • Sanitize the form data to keep things safe and clean.
  • Process the data, like sending an email, and then respond back to the JavaScript with success or error messages.

Displaying the Form:

  • Use a shortcode to easily add the form to any page or post.
  • The form includes fields for name, email, and message, and a submit button.

JavaScript Magic:

  • In your JavaScript file, listen for the form's submit event.
  • Prevent the default form submission to handle it via AJAX.
  • Send the form data to the server and update the page with the response, showing a success or error message without refreshing.

This setup allows your form to submit data asynchronously, providing a smoother user experience by avoiding page reloads.

Code

1<?php 2// Enqueue necessary scripts for AJAX 3function wp_dudecom_enqueue_ajax_scripts() { 4 wp_enqueue_script('jquery'); 5 wp_enqueue_script('wp-dudecom-ajax-script', get_template_directory_uri() . '/js/wp-dudecom-ajax.js', array('jquery'), null, true); 6 7 // Localize script to pass AJAX URL and nonce 8 wp_localize_script('wp-dudecom-ajax-script', 'wp_dudecom_ajax_object', array( 9 'ajax_url' => admin_url('admin-ajax.php'), 10 'nonce' => wp_create_nonce('wp_dudecom_ajax_nonce') 11 )); 12} 13add_action('wp_enqueue_scripts', 'wp_dudecom_enqueue_ajax_scripts'); 14 15// Handle AJAX form submission 16function wp_dudecom_handle_ajax_form_submission() { 17 // Check nonce for security 18 check_ajax_referer('wp_dudecom_ajax_nonce', 'security'); 19 20 // Sanitize and validate form data 21 $name = sanitize_text_field($_POST['name']); 22 $email = sanitize_email($_POST['email']); 23 $message = sanitize_textarea_field($_POST['message']); 24 25 // Process form data (e.g., send email) 26 $to = get_option('admin_email'); 27 $subject = 'New Form Submission'; 28 $body = "Name: $name\nEmail: $email\nMessage: $message"; 29 $headers = array('Content-Type: text/plain; charset=UTF-8'); 30 31 if (wp_mail($to, $subject, $body, $headers)) { 32 wp_send_json_success('Form submitted successfully.'); 33 } else { 34 wp_send_json_error('Failed to send email.'); 35 } 36 37 wp_die(); 38} 39add_action('wp_ajax_wp_dudecom_form_submit', 'wp_dudecom_handle_ajax_form_submission'); 40add_action('wp_ajax_nopriv_wp_dudecom_form_submit', 'wp_dudecom_handle_ajax_form_submission'); 41 42// Shortcode to display the form 43function wp_dudecom_ajax_form_shortcode() { 44 ob_start(); 45 ?> 46 <form id="wp-dudecom-ajax-form" method="post"> 47 <label for="name">Name:</label> 48 <input type="text" id="name" name="name" required> 49 50 <label for="email">Email:</label> 51 <input type="email" id="email" name="email" required> 52 53 <label for="message">Message:</label> 54 <textarea id="message" name="message" required></textarea> 55 56 <input type="submit" value="Submit"> 57 </form> 58 <div id="wp-dudecom-form-response"></div> 59 <?php 60 return ob_get_clean(); 61} 62add_shortcode('wp_dudecom_ajax_form', 'wp_dudecom_ajax_form_shortcode'); 63?> 64 65// JavaScript file (wp-dudecom-ajax.js) 66jQuery(document).ready(function($) { 67 $('#wp-dudecom-ajax-form').on('submit', function(e) { 68 e.preventDefault(); 69 70 var formData = { 71 action: 'wp_dudecom_form_submit', 72 security: wp_dudecom_ajax_object.nonce, 73 name: $('#name').val(), 74 email: $('#email').val(), 75 message: $('#message').val() 76 }; 77 78 $.post(wp_dudecom_ajax_object.ajax_url, formData, function(response) { 79 if (response.success) { 80 $('#wp-dudecom-form-response').html('<p>' + response.data + '</p>'); 81 } else { 82 $('#wp-dudecom-form-response').html('<p>' + response.data + '</p>'); 83 } 84 }); 85 }); 86}); 87

Instructions

File Location: Add the PHP code to your theme's functions.php file or a custom plugin file. Place the JavaScript code in a file named wp-dudecom-ajax.js within a js directory in your theme.

Prerequisites:

  • Ensure you have access to your WordPress theme files or a custom plugin.
  • Basic understanding of WordPress shortcodes and JavaScript.

Implementation Steps:

  1. Enqueue Scripts: Add the PHP code to enqueue jQuery and your custom JavaScript file. This ensures the necessary scripts are loaded on your site.
  2. Localize Script: Use wp_localize_script to pass the AJAX URL and a security nonce to your JavaScript file.
  3. Handle AJAX Submission: Implement the PHP function to handle form submissions. This includes checking the security nonce, sanitizing form data, and processing the data (e.g., sending an email).
  4. Add Shortcode: Use the provided shortcode function to display the form on any page or post. Insert the shortcode [wp_dudecom_ajax_form] where you want the form to appear.
  5. Create JavaScript File: Save the JavaScript code in a file named wp-dudecom-ajax.js in the js directory of your theme. This script handles the form submission via AJAX and updates the page with the server's response.
  6. Test the Form: Visit the page where you've added the shortcode and test the form submission to ensure it works correctly without reloading the page.

For assistance with implementation or more advanced functionality, consider using the services of wp-dude.com.