Loading the Form via AJAX

Ninja Forms is a JavaScript rendered application, which requires that the necessary script files be loaded onto the page for the form to render. Because of the way that WordPress (normally) renders content and enqueues scripts, this can create a complication when asynchronously loading a form as content in a “AJAX-based” theme (the registered scripts are usually not taken into account).

Therefore, the necessary script files must also be asynchronously loaded onto the page.

Note: The following is a proof of concept example, which may require customization based on the specifics of the implementation alongside a theme or plugin.

Step 1: Add a hook to return the necessary scripts.

The following hook determines which scripts to load for a given form.

add_action( 'init', function(){
if( ! isset( $_REQUEST[ 'async_form' ] ) ) return;
global $wp_scripts;
// Clear default loaded scripts.
unset( $wp_scripts->registered );
$form_id = absint($_REQUEST['form_id']);
$form = do_shortcode( "
$templates = ob_get_clean();
$response = [
'form' => $form,
'scripts' => $wp_scripts->registered,
'templates' => $templates
echo json_encode( $response );
add_action( 'wp_enqueue_scripts', function(){
// Make sure that backbone is enqueued on the page.
wp_enqueue_script( 'backbone' );

view raw
hosted with ❤ by GitHub

Step 2: Add a helper script to every page.

The following script asynchronously fetches the necessary scripts for a form and dynamically loads the results to the page.

view raw
hosted with ❤ by GitHub