9

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
  • Yes, it is. Or at least it should be possible. Any particular problems? Commented Jul 17, 2013 at 8:54
  • this seems to be a duplicate of drupal.stackexchange.com/questions/18867/… Commented Oct 17, 2013 at 1:44

2 Answers 2

6

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');
0
11

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);
1
  • 3
    this is a good example too Commented 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.