1

Sorry for asking this silly question.

I got stuck to include a javascript file in my html page in a php project. when I try this it works fine-

<script type="text/javascript" src="script.js"></script>

But when I want to load the script.js file from my js directory it does not work. I tried-

<script type="text/javascript" src="js/script.js"></script>

N.B: I have my js folder in the same myproject directory alongside my index.php and script.js is located inside the js folder.

2
  • When you load this page that the script is not loading on, what is the URL? Commented Nov 26, 2020 at 21:59
  • as I am running on my local machine the url is - localhost/myproject/index.php Commented Nov 26, 2020 at 22:03

4 Answers 4

2

Since there are subfolders in your project, to have js/script.js working you have to set your base path in your index.php like

echo '<base href="http://localhost/myproject/">';

then the following line as a normal html

<script type="text/javascript" src="js/script.js"></script>
Sign up to request clarification or add additional context in comments.

Comments

1

You can’t. PHP doesn’t execute Javascript code. Since Javascript and PHP are both scripting languages. You can use Jquery or AJAX or something like this to run js code

<script> 
 var my_javascript_var = "<?php echo 'some value I need on the client side' ; ?>"; 
alert (my_javascript_var ); 
</script> 

Comments

0

It might be access denied reading js folder or ..anything really. ...but the best you can do - open developer tools in your browser (hit F12 on Chrome), go to tab "Network" and refresh the page - you should see the reason why it doesnt load- status code will tell you.

enter image description here

Comments

0

Found out that I was calling my script in <head> tag of html which did not work for me. But calling it before closing of <body> tag worked!

Don't know why. Can anyone explain?

And obviously thanks everyone.

Comments

Your Answer

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.