1

i' m trying to load a dynamic value on every node of my site and i want to achieve this via ajax callback commands and writing custom module so i have a class in src/ajax folder of module like:

class TestCommand implements CommandInterface
{
..
  public function render() {
    return array(
      'command' => 'test',
      'text' => $this->message,
    );
  }
}

also a js file:

(function($, Drupal) {
  alert('loaded');
  /**
   * Add new command for reading a message.
   */
  Drupal.AjaxCommands.prototype.test = function(ajax, response, status){
    alert('called');
    console.log(response);
  }
})(jQuery, Drupal);

but i don't know where i am supposed to put this below lines to call command on every node/view. if i put this in mytheme_preprocess_node -checking with var_dump()- i can see
correct response but it doesn't call Drupal.AjaxCommands.prototype.test

  //where to put this lines to call test command on every node view.
  $response = new AjaxResponse();
  $response->addCommand( new TestCommand('someparam'));
  return $response;

js file is loaded because i get 'loaded alert'.

lots of examples on sites, call this via ajax callback in form. one have different approach but i don't know how to apply these solutions in my situation.

  • 1
    You put it in a controller like shown in the linked question, not the answers. Then this topic might be helpful how to trigger the ajax controller: drupal.stackexchange.com/questions/230312/… – 4k4 Jul 2 '19 at 16:37
  • @4k4 thank you. after reading your comment i end up with adding Drupal.ajax({url: endpoint}).execute(); at the end of js file and putting addcommand in controller. now it works. but i can not find how to pass node id via ajax to controller. also i am going to accept your answer if you post it because it solved my problem – user780 Jul 2 '19 at 18:38
2

You put it in a controller like shown in the linked question, not the answers. Then this topic might be helpful how to trigger the ajax controller: How to Trigger Existing, Non-Form Ajax from JavaScript Event

For passing the node ID to the controller use a route parameter:

myModule.myRoute:
  path: '/myajax/node/{node_id}'
  defaults:
    _controller: '\Drupal\myModule\MyController::getNode'
    _title: 'Node'
  requirements:
    _permission: 'access content'

Now you can add the node ID to the endpoint url

var url = '/myajax/node/' + node_id;
Drupal.ajax({url: url}).execute();

and received it by the controller:

public function getNode($node_id) {
| improve this answer | |

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.