1

I have the following js code according to es6.

(($, Drupal) => {
  Drupal.behaviors.mymodule = {
    attach: () => {
      document.querySelectorAll("a").forEach(element => {
        element.addEventListener("click", e => {
            fetch("/mypath", {
              method: "POST",
              body: JSON.stringify({
                path: $(this).attr("href")
              }),
            });
        });
      });
    }
  };
})(jQuery, Drupal);

and in the page controller:

public function content(\Symfony\Component\HttpFoundation\Request $request) {
  $path = $request->request->get('path');
}

But I am not getting the path. Can someone tell me how to get the path in my page controller?

2

Why do you want to use fetch() when your code is based on jQuery? There a plenty of examples using $.ajax() for POST requests:

/core/modules/quickedit/js/quickedit.es6.js

  $.ajax({
    url: Drupal.url('quickedit/metadata'),
    type: 'POST',
    data: {
      'fields[]': fieldIDs,
      'entities[]': entityIDs,
    },
    dataType: 'json',
    success(results) {
      // Store the metadata.
      _.each(results, (fieldMetadata, fieldID) => {
        Drupal.quickedit.metadata.add(fieldID, fieldMetadata);
      });

      callback(fieldElementsWithoutMetadata);
    },
  });

/core/modules/quickedit/src/QuickEditController.php

  public function metadata(Request $request) {
    $fields = $request->request->get('fields');
    ...

To make PHP accept POST parameters you need to specify the correct request headers. Default in $.ajax() is the contentType application/x-www-form-urlencoded

So when using fetch() start with this:

fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },

To get on par with $.ajax() you might need to tweak fetch() a little more or wait until core decides to change the Ajax libraries from jQuery to pure Javascript.

| 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.