28 February 2025

ajax_command_invoke is a powerful function in Drupal 7 that allows you to invoke JavaScript methods on DOM elements after an AJAX callback. These code examples will show you through setting up a custom module to demonstrate this functionality.

AJAX Callback: The mymodule_ajax_callback function returns an AJAX command to invoke a JavaScript method on a specific DOM element.
Source code viewer
  1. /**
  2.  * AJAX callback function.
  3.  */
  4. function mymodule_ajax_callback() {
  5. $commands = array();
  6.  
  7. // Add a command to invoke a JavaScript method on a specific element.
  8. $commands[] = ajax_command_invoke('#my-element', 'myCustomMethod', array('arg1', 'arg2'));
  9.  
  10. // Return the commands as a JSON response.
  11. return array('#type' => 'ajax', '#commands' => $commands);
  12. }
  13.  
  14. /**
  15.  * Implements hook_form_alter().
  16.  */
  17. function mymodule_form_alter(&$form, &$form_state, $form_id) {
  18. if ($form_id == 'your_form_id') {
  19. $form['your_element'] = array(
  20. '#type' => 'button',
  21. '#value' => t('Click me'),
  22. '#ajax' => array(
  23. 'callback' => 'mymodule_ajax_callback',
  24. 'wrapper' => 'my-element-wrapper',
  25. 'method' => 'replace',
  26. 'effect' => 'fade',
  27. ),
  28. );
  29.  
  30. $form['my_element_wrapper'] = array(
  31. '#type' => 'markup',
  32. '#markup' => '<div id="my-element">Original Content</div>',
  33. );
  34. }
  35. }
Programming Language: PHP
JavaScript Behavior: The JavaScript file defines a custom method myCustomMethod using $.fn to ensure it's available on jQuery objects. This method is then invoked on the element with ID #my-element.
Source code viewer
  1. (function ($) {
  2. Drupal.behaviors.myModuleBehavior = {
  3. attach: function (context, settings) {
  4. // Ensure the element exists in the current context.
  5. $('#my-element', context).once('myModuleBehavior', function () {
  6. // Define the custom method on the element using jQuery's fn.
  7. $.fn.myCustomMethod = function (arg1, arg2) {
  8. console.log('Method invoked with arguments:', arg1, arg2);
  9. // Perform some action, e.g., update the element's content.
  10. this.text('Updated with ' + arg1 + ' and ' + arg2);
  11. };
  12.  
  13. // Invoke the method to ensure it's attached correctly.
  14. $(this).myCustomMethod('initial', 'setup');
  15. });
  16. }
  17. };
  18. })(jQuery);
Programming Language: ECMAScript