I have a problem with an js file in php. if i include it like this:
?> <script type="text/javascript" href="file.js"></script> <?php
the file isn't included and i get an error that the function isn't defined.
When i try it this way:
<script type="text/javascript">
document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>');
</script>
the first tag in the document.write function closes <script type="text/javascript">
what is the correct way to do this?
thanks, sebastian
JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code.
Besides, PHP and JavaScript similarities, these two languages are a powerful combination when used together. Large numbers of websites combine PHP and JavaScript – JavaScript for front-end and PHP for back-end as they offer much community support, various libraries, as well as a vast codebase of frameworks.
PHP is completely irrelevant for what you are doing. The generated HTML is what counts.
In your case, you are missing the src
attribute. Use
<script type="text/javascript" src="file.js"></script>
I found a different solution that I like:
<script> <?php require_once("/path/to/file.js");?> </script>
Also works with style-tags and .css-files in the same way.
Pekka has the correct answer (hence my making this answer a Community Wiki): Use src
, not href
, to specify the file.
Regarding:
When i try it this way:
<script type="text/javascript"> document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>'); </script>the first tag in the document.write function closes
what is the correct way to do this?
You don't want or need document.write
for this, but just in case you ever do need to put the characters </script>
inside a script
tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>
. There are a couple of ways of doing that. One way is to escape the /
even though you don't need to:
<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
// ^--- note the seemingly-unnecessary backslash
</script>
Or if you're feeling more paranoid:
<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>
...since in each case, JavaScript sees the string as </script>
but the HTML parser doesn't.
In your example you use the href
attribute to tell where the JavaScript file can be found. This should be the src
attribute:
?> <script type="text/javascript" src="file.js"></script> <?php
For more information see w3schools.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With