Last active
April 18, 2024 18:12
-
-
Save stracker-phil/14f8b99c5d6d4133b7e8eda062ba0229 to your computer and use it in GitHub Desktop.
Load Forminator Form via Ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
} | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @dleigh - the
wp_ajax_<action>
hook is a special action provided by WordPress itself. You do not need to register an action with that name.The above action is called, when you make an HTTP request from your browser to the
admin-ajax.php
path and provide theaction: "my_get_support"
parameter. I.e. the following JavaScript line triggers that action for you:Hopefully, this makes the connection between JS and PHP a bit clearer for you.
Also, you might want to check out the official documentation with a lot more details here: