Skip to content

Instantly share code, notes, and snippets.

@tnchuntic
Forked from stracker-phil/forminator-via-ajax-script.js
Created November 23, 2021 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tnchuntic/b4d612c0a7182a141a71c50b900f9b54 to your computer and use it in GitHub Desktop.
Save tnchuntic/b4d612c0a7182a141a71c50b900f9b54 to your computer and use it in GitHub Desktop.
Load Forminator Form via Ajax
<?php
// The following Ajax handler is inside a loaded PHP file,
// such as a plugin, or in this sample, the functions.php file.
add_action('wp_ajax_my_get_support', 'ajax_my_get_support');
/**
* Ajax handler that gernates the form with all
* required JS files and CSS rules.
*/
function ajax_my_get_support() {
// Forminator needs the DOING_AJAX flag to
// correctly enqueue everything.
if ( ! defined( 'DOING_AJAX' ) ) {
define( 'DOING_AJAX', true );
}
if ( ! defined( 'WP_ADMIN' ) ) {
define( 'WP_ADMIN', true );
}
ob_start();
echo do_shortcode('[forminator_form id="1234"]');
// Add the JS files and inline styles, etc.
// Since this is an ajax request, this should only
// output Forminator-related code.
print_head_scripts();
do_action( 'wp_footer' );
print_late_styles();
print_footer_scripts();
$code = ob_get_clean();
wp_send_json_success( $code );
}
// This JS file is loaded by the theme:
(function() {
// The button with the CSS class "get-support" loads the form.
jQuery('.get-support').on('click', load_support_form);
// The form is displayed in a div tag with the CSS class "support-form".
function load_support_form() {
jQuery.get('/wp-admin/admin-ajax.php?action=my_get_support')
.then(function(response) {
jQuery('.support-form').html(response.data);
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment