Search code examples
jqueryajaxwordpresscontact-form-7smoothstate.js

Contact Form 7 throws 'wpcf7.initForm is not a function' error when loading page through AJAX (smoothstate.js)


I'm trying to implement Contact Form 7 on my wordpress website with smoothstate.js. The contact form works perfectly when the page where it is used on is loaded directly. However, if the page is loaded via AJAX the error 'wpcf7.initForm is not a function' appears.

I'm not a genius with AJAX, but my thought was to Re-initialise in the AJAX onAfter function. I tried this by using wpcf7InitForm(); but still no luck.

Any help on this topic will be greatly appreciated!

Here is my current AJAX code:

  //SmoothState Page Transitions

  $(function(){
    'use strict';
    var $page = $('#main'),
        options = {
          debug: true,
          prefetch: true,
          onStart: {
            duration:  800, // Duration of our animation
            render: function ($container) {
              // Add your CSS animation reversing class

              $container.addClass('is-exiting');

              // Restart your animation
              smoothState.restartCSSAnimations();
            }
          },
          onReady: {
                duration: 0,
                render: function($container, $newContent) {
                    // Remove your CSS animation reversing class
                    $container.addClass('is-loaded');

                    setTimeout(function(){
                      $container.addClass('unload');
                    }, 600);

                    setTimeout(function(){
                      $container.removeClass('is-loaded unload');
                    }, 900);


                    // Inject the new content
                    $container.html($newContent);
                }
            },
            onAfter: function($container) {
              $container.removeClass('is-exiting');
               $('div.wpcf7 > form').wpcf7InitForm();
               $(window).data('plugin_stellar').refresh();
            }
        },
        smoothState = $("#main").smoothState(options).data("smoothState");
      });


Solution

  • There was a change to Contact Form 7 in v4.8 that got rid of jquery.form.js so the wpcf7InitForm() function no longer works. However, a new init function was brought back in v4.8.1

    wpcf7.initForm
    

    Use this function instead:

    function initContactForm() {
     $( 'div.wpcf7 > form' ).each( function() {
      var $form = $( this );
      wpcf7.initForm( $form );
      if ( wpcf7.cached ) {
       wpcf7.refill( $form );
      }
     });
    }
    

    Call it in onAfter and it should solve your problem.

    Here's the discussion on the Contact Form 7 support forum: https://wordpress.org/support/topic/init-function-wpcf7initform/