Last updated on October 18, 2023

WP Forms AJAX submissions

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Submit forms without page refresh.

To enable AJAX submissions for WP Forms, you can use the wp_ajax_ and wp_ajax_nopriv_ hooks provided by WordPress. These hooks allow you to handle AJAX requests from both logged-in users and non-logged-in users respectively.

Here’s an example code snippet that demonstrates how to handle AJAX submissions for WP Forms:

// Enqueue JavaScript file for AJAX handling
function wpsnippets_enqueue_scripts() {
    wp_enqueue_script( 'wpsnippets-ajax', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'wpsnippets_enqueue_scripts' );

// Handle AJAX form submission
function wpsnippets_handle_ajax_form_submission() {
    // Check if the AJAX request is for the WP Forms submission
    if ( isset( $_POST['action'] ) && $_POST['action'] === 'wpsnippets_ajax_form_submission' ) {
        // Process the form data
        // ...

        // Return the response
        wp_send_json_success( 'Form submitted successfully!' );
    }
}
add_action( 'wp_ajax_wpsnippets_ajax_form_submission', 'wpsnippets_handle_ajax_form_submission' );
add_action( 'wp_ajax_nopriv_wpsnippets_ajax_form_submission', 'wpsnippets_handle_ajax_form_submission' );

In this example, we first enqueue a JavaScript file called ajax.js using the wp_enqueue_script() function. This file will handle the AJAX request and response.

Next, we define a function wpsnippets_handle_ajax_form_submission() to handle the AJAX form submission. Inside this function, you can process the form data as per your requirements.

Finally, we use the wp_ajax_ and wp_ajax_nopriv_ hooks to register the wpsnippets_handle_ajax_form_submission() function for both logged-in and non-logged-in users.

To trigger the AJAX form submission, you can use JavaScript/jQuery to make an AJAX request to the server. Here’s an example of how you can do it using jQuery:

jQuery(document).ready(function($) {
    $('#my-form').on('submit', function(e) {
        e.preventDefault();

        var formData = $(this).serialize();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData + '&action=wpsnippets_ajax_form_submission',
            success: function(response) {
                // Handle the AJAX response
                console.log(response);
            }
        });
    });
});

In this example, we listen for the form submission event using the submit event handler. When the form is submitted, we prevent the default form submission behavior using e.preventDefault().

Then, we serialize the form data using $(this).serialize() and make an AJAX request to the server using $.ajax(). The ajaxurl variable is a global variable provided by WordPress that contains the URL to the AJAX handler.

Once the AJAX request is successful, the success callback function is executed, where you can handle the response as needed. In this example, we simply log the response to the console.

This code snippet allows you to handle WP Forms submissions via AJAX, providing a smoother user experience and eliminating the need for page reloads.

Examples

Example 1: AJAX form submission with WP Forms

This example demonstrates how to submit a WP Forms form using AJAX. The code snippet below shows how to enqueue the necessary JavaScript file and initialize the AJAX form submission.

function wpsnippets_enqueue_scripts() {
    wp_enqueue_script( 'wpsnippets-ajax-form', get_template_directory_uri() . '/js/ajax-form.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'wpsnippets-ajax-form', 'wpsnippets_ajax_form', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'wpsnippets_ajax_form_nonce' ),
    ) );
}
add_action( 'wp_enqueue_scripts', 'wpsnippets_enqueue_scripts' );

function wpsnippets_ajax_form_submission() {
    check_ajax_referer( 'wpsnippets_ajax_form_nonce', 'nonce' );

    // Process form submission here

    wp_send_json_success( 'Form submitted successfully!' );
}
add_action( 'wp_ajax_wpsnippets_ajax_form_submission', 'wpsnippets_ajax_form_submission' );
add_action( 'wp_ajax_nopriv_wpsnippets_ajax_form_submission', 'wpsnippets_ajax_form_submission' );

The wpsnippets_enqueue_scripts function enqueues the ajax-form.js file and localizes it with the necessary AJAX parameters. The wpsnippets_ajax_form_submission function processes the form submission and sends a JSON response.

Example 2: Custom AJAX form validation with WP Forms

This example demonstrates how to perform custom form validation before submitting the WP Forms form using AJAX. The code snippet below shows how to add a custom JavaScript validation function and modify the form submission handler.

function wpsnippets_enqueue_scripts() {
    wp_enqueue_script( 'wpsnippets-ajax-form', get_template_directory_uri() . '/js/ajax-form.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'wpsnippets-ajax-form', 'wpsnippets_ajax_form', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'wpsnippets_ajax_form_nonce' ),
    ) );
}
add_action( 'wp_enqueue_scripts', 'wpsnippets_enqueue_scripts' );

function wpsnippets_ajax_form_submission() {
    check_ajax_referer( 'wpsnippets_ajax_form_nonce', 'nonce' );

    // Custom form validation
    if ( empty( $_POST['name'] ) ) {
        wp_send_json_error( 'Name field is required.' );
    }

    // Process form submission here

    wp_send_json_success( 'Form submitted successfully!' );
}
add_action( 'wp_ajax_wpsnippets_ajax_form_submission', 'wpsnippets_ajax_form_submission' );
add_action( 'wp_ajax_nopriv_wpsnippets_ajax_form_submission', 'wpsnippets_ajax_form_submission' );

In this example, a custom form validation is added to check if the name field is empty. If the validation fails, an error response is sent back to the client. Otherwise, the form submission is processed as usual.

Example 3: Redirect after successful AJAX form submission with WP Forms

This example demonstrates how to redirect the user to a specific page after a successful AJAX form submission using WP Forms. The code snippet below shows how to modify the form submission handler to include the redirect logic.

function wpsnippets_enqueue_scripts() {
    wp_enqueue_script( 'wpsnippets-ajax-form', get_template_directory_uri() . '/js/ajax-form.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'wpsnippets-ajax-form', 'wpsnippets_ajax_form', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'wpsnippets_ajax_form_nonce' ),
    ) );
}
add_action( 'wp_enqueue_scripts', 'wpsnippets_enqueue_scripts' );

function wpsnippets_ajax_form_submission() {
    check_ajax_referer( 'wpsnippets_ajax_form_nonce', 'nonce' );

    // Process form submission here

    wp_send_json_success( array(
        'message'  => 'Form submitted successfully!',
        'redirect' => home_url( '/thank-you' ),
    ) );
}
add_action( 'wp_ajax_wpsnippets_ajax_form_submission', 'wpsnippets_ajax_form_submission' );
add_action( 'wp_ajax_nopriv_wpsnippets_ajax_form_submission', 'wpsnippets_ajax_form_submission' );

In this example, the form submission handler includes a redirect parameter in the success response. The client-side JavaScript can then handle the redirect after displaying the success message.

Last updated on October 18, 2023. Originally posted on December 11, 2023.

Leave a Reply

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