1

my phtml file

<div class="home-del-days-main-cont">
            <div class="hof-changeoutletcontent">
                <div class="h-find-de-day">
                    <h2><?php  echo __("Enter your postcode to find delivery days ");?></h2>
                    <div>
                        <p style="text-align: center;"><?php // echo __("Please enter a delivery postcode to see delivery days.");?></p>
                    </div>
                </div>
            </div> 
            <div>
                <div class="h-news-frm">
                    <div>
                        <div class="h-news-left">
                            <input id="home-postcode" name="postcode" type="text" placeholder="<?php echo __("Enter your postcode");?>">
                        </div>
                        <div class="h-news-right" style="float: left;">
                            <a href="javascript:void(0)" id="zipcode-submit-button"><?php echo __("Find delivery days");?></a>
                        </div>
                        <div id="zipcode-error" style="display: none;" class="mage-error zipcode-error"><p><?php echo __('Enter your delivery Post-code.') ?></p>
                        </div>
                        <div id="zipcode-error-wrongformat" style="display: none;" class="mage-error zipcode-error-wrongformat" ><p><?php echo __('Please enter the postcode in the correct format e.g. AB12 3CD.') ?></p>
                        </div>
                        <div id="zipcode-error-notfound" style="display: none;" class="mage-error zipcode-error-notfound" ><p><?php echo __('Unable to find Post-code Delivery.') ?></p>
                        </div>
                    </div>
                </div>
            </div>
</div>
<script type="text/javascript">
    require(['jquery','https://maps.googleapis.com/maps/api/js?key=AIzaSyC17wzmxfwqRcjVmbanfmsPGbT_Ngl2d7s'
        ], function($, googleMapApi) {
        $("#zipcode-submit-button").on('click', function () {
            var zipcodecurrentlocation = $('#home-postcode').val();
            if(zipcodecurrentlocation=="") {
                $(".h-news-frm #zipcode-error").show();
                setTimeout(function() { $(".h-news-frm #zipcode-error").hide(); }, 5000);
                return false;
            }
            zipcodecurrentlocation = zipcodecurrentlocation.replace(/ /g,'');
            zipcodecurrentlocation = zipcodecurrentlocation.toUpperCase();
            zipcodecurrentlocation = zipcodecurrentlocation.substring(0, zipcodecurrentlocation.length - 3) + " " + zipcodecurrentlocation.substring(zipcodecurrentlocation.length, zipcodecurrentlocation.length - 3);
            isSuccessApi = 1;
            validateZipcode(zipcodecurrentlocation);
            function validateZipcode(zipcodecurrentlocation) {
                var data = {'zipcode': zipcodecurrentlocation};
                $.ajax({
                    url:'<?php echo $this->getUrl("zipcode/zipcode/getvendor") ?>',
                    type:'POST',
                    showLoader: true,
                    dataType:'json',
                    data: data,
                    complete: function(data) {
                    //console.log(data.responseJSON.validate);
                    if (data.responseJSON.validate!=0) {
                        window.location.href = data.responseJSON.redirecturl;
                    }else{
                        $(".h-news-frm #zipcode-error-notfound").show();
                        setTimeout(function() { $(".h-news-frm #zipcode-error-notfound").hide(); }, 5000);
                        errorGenerate = 1;
                        return false;
                    }
                    
                    },
                    error: function (xhr, status, errorThrown) {
                        console.log('Error happens. Try again.');
                        errorGenerate = 1;
                        return false;
                    }
                });
            }
        });
    });
</script>

I don't want to use inline script inside my phtml file, how can i use external js file to achive the same.

Thank you!

3 Answers 3

0

Using layout :

In your layout file you need to add the code below:

<?xml version="1.0"?>
 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <!--  add css and js file on page  -->
     <head>
    <!--  css file  -->
      <css src="Vendorname_Modulename::css/barstyle.css"/>
    <!--  js file  -->
      <script src="Vendorname_Modulename::js/barstyle.js"/>
     </head>
 </page>
2
  • Hi @ndev, Thanks for your information but i don't have any layout file for that phtml file
    – Mani
    Commented Sep 7, 2022 at 13:47
  • @Mani that's shouldn't be possible. Any template has a layout to tell where the template is used.
    – Claims
    Commented Sep 7, 2022 at 15:51
0

The best way to add js in phtml is via requirejs

Theme solution :

Supposing that your js file is: myfile.js

app/design/frontend/{Vendor}/{theme}/requirejs-config.js

var config = {
    map: {
        '*': {
            myscript: 'js/myfile'
        }
    }
};

app/design/frontend/{Vendor}/{theme}/web/js/myfile.js

define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert("Yes, got it.");
       }
});

app/design/frontend/{Vendor}/{theme}/Magento_Theme/templates/{yourfile}.phtml

<?php if(condition here): ?>
    <script>
        require(['jquery', 'myscript'], function($, myscript) {
            myscript();
        });
    </script>
<?php endif;?>

Clear Magento Cache and run static content deploy: php bin/magento setup:static-content:deploy

0

For this type of development, there are various solutions, but I recommend using the below solution for more extensibility in the future:

  1. You can create a jquery widget for the selector - #zipcode-submit-button, the widget will be initialized when that element has been loaded in the dom.

  2. I hope you have created a module and have a phtml file , in that phtml file at the end add this script tag:

    <script type="text/x-magento-init">
    {
        "#zipcode-submit-button" : {
            "Custom_Module/js/custom-widget": {}
        }
    }
    
  3. Create a JS file in this path inside your module -> view/frontend/web/js/custom-widget.js

    define([
    'jquery'
    ], function ($, _) {
    'use strict';
    
    $.widget('mage.customWidget',{
    
    _create: function(config,element) {
    
       //Please define your logic here or migrate your logic from phtml file here
       //Example logic please see below
       $("#zipcode-submit-button").on('click', function () {
        var zipcodecurrentlocation = $('#home-postcode').val();
        });
    
     },
     });
     return $.mage.customWidget;
     });
    
  4. If you are in developer mode simple cache flush should work if there is no other 3rd party cache treatment or deploy using your own strategy.

Please do let me know if it works or not or in case you need more help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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