3

I have some custom Javascripts. at the part of code I want to leverage Drupal AjaxResponse but looks like it's only working when there Triggered by Drupal Form's ajax element. ( my ajax call verb is POST)

I mean when I can this endpoint from js, I see the response in browser network, but it does not work and not applied.

Response:

[{"command":"alert","text":"just to test trigger Drupal command"}]

Route:

picture_park.preset_selector:
  path: '/admin/media/picture-park/preset-selector'
  defaults:
    _title: 'Preset Selector Picture Park images as Media'
    _controller: '\Drupal\media_entity_remote_picture_park\Controller\MediaController::presetSelector'
  requirements:
    _permission: 'Remote Image Picture Park: Create new media'

Controller method:

  public function presetSelector(): AjaxResponse
  {
    $response = new AjaxResponse();
    $response->addCommand(new AlertCommand("just to test trigger Drupal command"));

    return $response;
  }

JS:

  function postData(data) {
    return jQuery.post("/admin/media/picture-park/preset-selector?_wrapper_format=drupal_ajax", {
      "data": data,
      "js": true,
      "_drupal_ajax": 1,
    })
  }

So, what I'm looking for is, how can I make Drupal AjaxResponse runs and get executed when the endpoint is called from a custom js?

3
  • 1
    The simplest way is Drupal.ajax({url: endpoint}).execute(); where endpoint is the URL of your Ajax controller. See drupal.stackexchange.com/questions/230312/…
    – 4uk4
    Commented Aug 19, 2022 at 6:33
  • Thank you @4uk4. sounds feasible. how can i add payload to the request?
    – Yuseferi
    Commented Aug 19, 2022 at 7:49
  • @4uk4 I found it. it can be done with submit param. thanks for hint
    – Yuseferi
    Commented Aug 19, 2022 at 7:57

1 Answer 1

6

You should be able to trigger the commands with the following:

ajaxObject = Drupal.ajax({
  url: "",
  base: false,
  element: false,
  // Use the 'submit' key to pass data.
  // Leave this key out if not passing any data.
  submit: {"data":"test"},
  progress: false
});

// Trigger ajax commands.
ajaxObject.success(data, "success");

Add the above to a success callback of your Ajax response. Note you may also need to add the following to process any Ajax inserted content:

Drupal.attachBehaviors();
2
  • Thank you!. how request payload set? I didn't find data in Drupa.ajax . sounds like it needs Ajax. options to pass data.?
    – Yuseferi
    Commented Aug 19, 2022 at 7:50
  • I found it. it's with submit key.
    – Yuseferi
    Commented Aug 19, 2022 at 7:57

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.