8

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);
}
5

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');
| improve this answer | |
10

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) {
        alert(response.value1);
        alert(response.value2);
    }
})(jQuery, Drupal);
| improve this answer | |
  • 3
    this is a good example too – Rotari Radu Nov 4 '14 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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