Ajax Example

This example was updated on 1 June 2021 to make it compatible with CF7 version 5.4+

If you want to make it work with older versions of CF7, use wpcf7.initForm($form); instead of wpcf7.init($form[0]);

In this example we will create a button (#load_ajax_form). After clicking the button, the form with ID 242 will be loaded asynchronously into a div (#ajax_content)

Create a page template and include the code below where you would like the button to appear.

<button id="load_ajax_form">Load Ajax Form</button>
<div id="ajax_content"></div>
<script>
    (function($) {
        $('#load_ajax_form').click(function() {

            // The data to pass along with the Ajax request

            var data = {
                'action' : 'load_form', // This will create 2 hooks in PHP: "wp_ajax_load_form" and "wp_ajax_nopriv_load_form"
                'form_id' : 242 // replace this with the id of the form you actually want to load
            };

            // Do the actual Ajax request

            $.post(wpcf7cf_global_settings.ajaxurl, data, function(response) {

                // load the HTML part of the form
                $('#ajax_content').html(response);
    
                $form = $('#ajax_content .wpcf7-form').eq(0);
    
                // register all the necessary events on the Contact Form 7 form
                wpcf7.init($form[0]);
    
                // register all the necessary events for the conditional logic to work
                wpcf7cf.initForm($form);

            });

        });
    })( jQuery );
</script>

As you can see we are going to send an Ajax request with an action ‘load_form’ and a form_id 242.

Now let’s make sure the server can handle this request. In your functions.php file, add this code:

add_action( 'wp_ajax_load_form', 'ajax_load_form' );
add_action( 'wp_ajax_nopriv_load_form', 'ajax_load_form' );
function ajax_load_form() {
  echo do_shortcode('[contact-form-7 id="'.$_POST['form_id'].'"]');
  die();
}

And, you should be set.