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.
-
When you load this page that the script is not loading on, what is the URL?mikeroq– mikeroq2020年11月26日 21:59:06 +00:00Commented Nov 26, 2020 at 21:59
-
as I am running on my local machine the url is - localhost/myproject/index.phpRaju Ahmed– Raju Ahmed2020年11月26日 22:03:23 +00:00Commented Nov 26, 2020 at 22:03
4 Answers 4
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>
Comments
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
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.
Comments
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.