Please try this,
There are two ways to include javascript from the template in Magento 2: the <script type="text/x-magento-init"> and the data-mage-init attribute. Either way can be used to pass data to the script within the json definition. For example, using the x-magento-init script tag, in the template you have:
<script type="text/x-magento-init">
{
"*": {
"js/example": {
"a": "<?php echo 'Hello from template' ?>"
}
}
}
</script>
And in the JS file, you have:
define([
'jquery'
], function ($) {
'use strict';
return function (config) { console.log(config); // will output {a: "Hello from template"} alert(config.a); // would be equal to alert("Hello from template");
}
});