0

JS for my main page is working..for example, I am using main_file.js for my default loaded page. Which is actually working properly. but I have a search option on my default page which leads to some other .phtml file (named as second..phtml). js used for that .phtml is not working. even I have included it in the .xml file too.

This is how I declare js in .xml file for my default page .phtml

<script src="[CP_MODULE]::js/main_quickorder.js"/>

this how I declare js in .xml file of second .phtml.

<script src="[CP_MODULE]::js/test2.js"/>

first one is working properly but second one is not working.

3
  • It feels like a bit small amount of info, you should post how your components are declared and defined (xml, phtml, js) Considering the amount info you gave it can be anything a typo or you put your code in wrong xml file or you initialized the javascript in an invalid way Commented Mar 18, 2021 at 21:48
  • oky...I will try my level best to explain it again Commented Mar 18, 2021 at 21:49
  • Check in console that file is called or not Commented Mar 19, 2021 at 3:27

2 Answers 2

0

This is easy to check than you thought.

  1. First, you need to make sure that the JS file is in the page - Meaning your layout get updated, your definition is correct.

So you can search in the page for that file's name (view-source with ctrl-U or search in Element tab)

  1. When we're sure the file is in the page, check the console, see if any red error happen? If so, then your JS is running, it just not running properly.

  2. When 1 and 2 are done -> we know the file is in the page, there's no error. It's time to enter some code to signal that the JS file is working.

You can use console.log or alert to know that your file is working properly.

  1. If none of those steps help, you may loading the file improperly. You need to provide more information about the xml, how you define layout, phtml and js files.
answered Mar 19, 2021 at 1:11
-1

You can also load the JS in the phtml template this way:

<script type="text/javascript">
require([
 '[CP_MODULE]::js/test2.js'
], function() {})
</script>

and make sure the test2.js file is in app/code/CP/MODULE/view/frontend/web/js/test2.js

answered Mar 19, 2021 at 6:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.