Last active
January 1, 2023 15:43
-
-
Save adeel-raza/c0dafb16c93d1440abd8315fe99cce29 to your computer and use it in GitHub Desktop.
A very simple function to execute custom JS after an ajax request with a specific WordPress action is triggered
This file contains 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 | |
add_action( 'wp_enqueue_scripts', 'myprefix_add_custom_js'); | |
function myprefix_add_custom_js() { | |
wp_add_inline_script( 'jquery', | |
' | |
jQuery(function($) { | |
/** | |
* catch AJAX complete events, to catch wordpress actions | |
* @param {jQuery.Event} event | |
* @param {jqXHR} xhr XmlHttpRequest object | |
* @param {Object} ajaxOpts options for the AJAX request | |
*/ | |
$(document).ajaxComplete(function(event, xhr, ajaxOpts) { | |
// Specify the AJAX action after which you want to execute your JS | |
if ("data" in ajaxOpts && ajaxOpts.data.indexOf("action=wp_pro_quiz_load_quiz_data") != -1) { | |
// JS Code that runs after the specified WP action | |
alert(1) | |
} | |
}); | |
}); | |
' | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Place this in your WP child theme's functions.php file and enjoy playing around.
The default example will show an alert message when the LearnDash Quiz start button is clicked on a LearnDash Quiz page. Note that in this example we target the AJAX request triggered after a user clicks the Start Quiz button, the ajax request contains the action
wp_pro_quiz_load_quiz_data
. You can apply your own custom JS after an AJAX request where a different action is called.Any queries, reach me out via my site,
https://elearningevolve.com/contact/