3

Use case: You call ajax, and want to call some custom javascript (js) with some parameters as part of the response.

Issue: Two different solutions exist.

Questions:

  • is there a preferred method or is this just a matter of style?
  • are there differences in the benefits of each approach?

(there are a few questions eg 1 which supply different methods)

(Sorry these two examples may not be perfect - so feel free to edit)

Extend JQuery: $.fn

php:

$commands[] = ajax_command_invoke(
  NULL, 
  'mymodule_command', 
  array($data)
);

js:

$.fn.mymodule_command = function(data) {
  // dialog ajax id
  var dialogAjaxId = data.id;
  var blah = JSON.stringify(data.values);

};

Extend Drupal: Drupal.ajax.prototype

see this example

php:

$commands[] = array(
  'command' => 'mymodule_command',
  'arguments' => array(...),
);

js:

Drupal.ajax.prototype.commands.mymodule_command = function(ajax, response, status) { 
  console.log('mymodule_command', ajax, response, status);
  console.log('arguments', response.arguments);
};
2

Extending Drupal.ajax.prototype is the way Drupal and almost every contrib handles this.

is there a preferred method or is this just a matter of style?

are there differences in the benefits of each approach?

The preferred method would be the latter. However, note that both methods are not the same. Ajax commands are passed through ajax_render() function, which allows modules to alter the ajax commands by implementing hook_ajax_render_alter(&$commands). If you use the former method, you will see the invoke as the command, which makes it difficult to figure out the exact invoke command.

For Javascript eyes, it's just a matter of $.fn (shorthand for jQuery.prototype) vs Drupal.ajax.prototype.

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.