How to add custom js file from phtml with php variable
Do you want to pass your PHTML variable in your custom JS file?
Step 1. Remove your JQuery code from phtml and create a js file in web/js/, You can create that file in the theme or module.
define(['jquery'], function($) { 'use strict'; return function (config) { // You can access your phtml variable in js like this var myvalue = config.yourphtmlVariable; console.log(myvalue); //123 } });
Step 2. Include your JS file from your PHTML. add blow code in your phtml file and pass your variable in js
<?php $yourphtmlVariable = 123; ?> <script type="text/x-magento-init"> { "*": { "Vendor_Module/js/custom-js": { "yourphtmlVariable": <?= /* @escapeNotVerified */ json_encode($yourphtmlVariable); ?> } } } </script>