Pass data from phtml to javascript in Magento2

In this topic we describes different ways to pass data from phtml to javaScript in Magento 2 using Declarative Notation. Subscribe to Bethos for all the Magento2 problems and customizations.

If you do not know about calling and initializing javascript, please refer Calling and initializing JavaScript in Magento2 blog to know about it.

Types of ways to pass data from phtml to Javascript:

As mentioned in the above referenced block, there are two ways to call js in Declarative notation.

Using <script type="text/x-magento-init"> ... </script> tag:

In the above example, we passed the static and php values from phtml to javascript.

Using the data-mage-init attribute:

In below example, we used data-mage-init-attribute to pass data from phtml to javascript.

Finally in your javascript, you can get the passed data using config variable.

For Example:

In the config variable it will pass the data as json from phtml to javascript as in below example. You can access the passed value as JSON data in your custom javascript file like above example.

If you need more help regarding this post, feel free to ask in the Comments section below.

I would be happy to solve your queries.

1 thought on “Pass data from phtml to javascript in Magento2”

Leave a Comment