How to Pass Data from PHP to JavaScript in Magento 2

How to Pass Data from PHP to JavaScript in Magento 2

No other platform offers you the power to create a unique and engaging shopping experience as Magento does!

Rich, seamless third-party integrations, out-of-the-box features, a flexible headless architecture, and an unlimited ability for customization are the most favourite features of mine!

Compatibility with scripting languages is the greatest advantage of Magento 2.

JavaScript is client-side and PHP is the server-side scripting language. Need often arrives to pass data from PHP to javascript in Magento 2, especially when data has to be fetched on the frontend in JS file from the backend.

For instance, I’ve created one configuration using XML and my requirement is if the extension is enabled then the value should be displayed on the frontend.

You can use this solution, for example, when you want to print the value of default country selected. One step forward, you can implement conditions to show the list of states if that country is selected. In that case, pass the value of condition instead of name in the below code.

Steps to Pass Data from PHP to JavaScript in Magento 2

  1. Create di.xml in app/code/Vendor/Module/etc/frontend/
  2. Create GetCustomValue.php in app/code/Vendor/Module/Model/

  3. Create custom.js  in app/code/Vendor/Module/view/frontend/web/js/

Seems complicated at first but using the above solution you can easily crack it!

Still, if you have any doubts, do mention them in the Comments section below 🙂

I would be happy to help.

Feel free to share the solution with Magento community via social media.

Thank You.

Get Weekly Updates

Never miss Magento tips, tricks, tutorials, and news.

Thank you for subscribing.

Something went wrong.

5
(based on 13 Reviews)

Krishna is a Magento developer at Meetanshi. She is always ready to learn new things. Apart from work, she likes to read books and spend time with family.

Leave a reply:

Your email address will not be published.