Skip to content

Instantly share code, notes, and snippets.

@adeel-raza
Last active January 1, 2023 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adeel-raza/c0dafb16c93d1440abd8315fe99cce29 to your computer and use it in GitHub Desktop.
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
<?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)
}
});
});
'
);
}
@adeel-raza
Copy link
Author

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment