Is it possible to invoke a custom JS function in an AJAX callback?

function MY_MODULE_ajax_callback() {
  // Define a new array to hold our AJAX commands.
  $ajax_commands = array();

  // Create a new AJAX command that replaces the #page text with our own text.
  $ajax_commands[] = [CUSTOM JS FUNCTION]

  // Return our commandS
  return array('#type' => 'ajax','#commands' => $commands);

2 Answers 2


You can't run an arbitrary script, but if you can wrap your JS functionality in a jQuery plugin you can use ajax_command_invoke to get the same effect, e.g.

$selector = 'body';
$method = 'myJqueryPlugin';
$args = array('arg1', 'arg2');

$ajax_commands[] = ajax_command_invoke($selector, $method, $args);

When that comes out in the front end it'll execute something equivalent to

$('body').myJqueryPlugin('arg1', 'arg2');

Yes, it is.

Code sample:

$commands = array();
$commands[] = array(
    'command' => 'your_js_callback', // the name of your javascript callback
    'value1'  => 'My first value',
    'value2'  => 'My second value',

JS Code:

(function($, Drupal) {
    Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
})(jQuery, Drupal);
  • 3
    this is a good example too Nov 4, 2014 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.