-1

I have form. On form submit I would like to call JS function by passing it's value form PHP.

I know we can do on Submit onClick event of form. But I have different requirement.

I need to pass some variables from PHP to JS function/file & process them

   public function submitForm(array &$form, FormStateInterface $form_state) {
      // Call JS Function from PHP
    }

I'm integrating GA Events. So need to pass variables.

closed as unclear what you're asking by Pierre.Vriens, DRUPWAY, sanzante, Neograph734, kiamlaluno Apr 23 '18 at 15:47

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • Your code doesn't make sense - do you want to do a redirect, or do you want to do JS? If you want to do both, the JS would go on the 'welcome' page you have redirected to, not on the page you are redirecting from. – Jaypan Apr 9 '18 at 2:48
  • @Jaypan I updated the question. I will get some values in PHP then I need to pass it to JS file or Function. So can process it's value – Julia Apr 9 '18 at 2:51
  • The simple answer is that you cannot call a JS function from a submit handler. Can you update the question and tell us what you are trying to do? Right now, you are telling us how you are trying to do something, but you haven't explained what that something is. – Jaypan Apr 9 '18 at 2:53
  • @Jaypan. I'm intergrating GA Events. Some of the events I'm able to add via JS. But some requires on PHP Side. Not able to find perfect library via Composer module. – Julia Apr 9 '18 at 2:58
  • That's not really enough to understand what you are trying to do. But you can pass variables from php to JS using drupalSettings: drupal.org/node/2274843 – Jaypan Apr 9 '18 at 3:02
1

In your module call hook_page_attachments_alter(&$build), inside the function call:

$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

and you can access it directly from your js like below

Where 'bar' is some calculated value.

Then cuddly-slider.js will be able to access

drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').

Reference: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

  • 2
    Drupal 8 doesn't have drupal_add_js any more – Clive Apr 9 '18 at 10:53
  • I modified my code for Drupal 8. – Karthi Apr 9 '18 at 11:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.