Ajax Example

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>
    (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
                $form = $('#ajax_content .wpcf7-form').eq(0);
                // register all the necessary events on the Contact Form 7 form
                // register all the necessary events for the conditional logic to work


    })( jQuery );

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 404 "Not Found"].'"]');

And, you should be set.