0

I am new in magento2. I want to create an info link below every product. after clicking a link I want to show some info. I have created PHP file for anchor tag structure like \app\code\Vendor\Module\Block\Catalog\Product\info.php after clicking the link it calling js function from phtml file but I don't understand how to write js file inside js folder;

0

VendoreName/ModuleName/view/frontend/layout

default_head_blocks.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="VendoreName_ModuleName::js/our_module_js_file_name.js" />
    </head>
</page>

VendoreName/ModuleName/view/frontend/web/js

our_module_js_file_name.js

require(["jquery"],
    function($){
        $('#myAnc').click(function() {
            alert("hello i am click");
        });

})

in your phtml file

<a id="myAnc" href="#">Click Here</a>

run magento command

php  bin/magento s:up 

php bin/magento s:s:d -f 

php bin/magento c:c
0

You can call JS and PHTML file from your custom module layout file:

/app/code/Vendor/Module/view/frontend/layout/module_index_index.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="1column">
    <head>
       <script src="Vendor_Module::js/pro_info.js"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="custom_view" template="Vendor_Module::pro_info.phtml"></block>
        </referenceContainer>
    </body>
</page>

/app/code/Vendor/Module/view/frontend/templates/pro_info.phtml

<?php $proId = 12; // Here you can get dynamic Product Id. 
<a href="#" onclick="getProInfo(<?= $proId; ?>);">Get Product Info.</a>

/app/code/Vendor/Module/view/frontend/web/js/pro_info.js

function getProInfo(proId) {
    console.log(proId);
}

I hope it will helpful for you.

4
  • thanks for answer but i have write anchor tag inside php file in block folder and js inside phtml file but it couldn't call js function giving error like: Uncaught ReferenceError: showInfo is not defined at HTMLAnchorElement.onclick – shital Feb 17 '20 at 11:35
  • Can you please post your code? – Rohit Feb 17 '20 at 11:58
  • It's not proper way to use HTML code in php file, instead of block you can write anchor tag or HTML in PHTML file, you can call block function from PHTML file using $block->getProInfo() and get data in PHTML file and pass in JS function. – Rohit Feb 17 '20 at 12:10
  • okk i will try this. – shital Feb 18 '20 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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