-5

Is it valid to use both javascript and php in the same html file and still have your code working?

3
  • 4
    Yes. (I'm not sure if this is a trick question.) Commented Dec 2, 2011 at 18:40
  • 3
    Please expand the question. Also, you should read the FAQ. stackoverflow.com/faq and how to ask questions. meta.stackexchange.com/questions/18584/… Finally, did someone really upvote this question?! Commented Dec 2, 2011 at 18:40
  • Yes, but only if you set HTML files to be handled by PHP. Otherwise the PHP code will simply be displayed instead of parsed. Commented Dec 2, 2011 at 18:56

5 Answers 5

6

php is server-side and javascript is client-side. The two do not conflict at all because php is used to generated the page which may or may not include javascript. Then once the page is served up to the client (no php is passed to the front end), then the javascript will run on the client side.

0

You can have valid JavaScript and valid php in the same file yes. But php is run server side and in this context JavaScript is normally run on the client. They can not directly interact if that is what you are asking.

0

Yes. Your PHP will be parsed by the PHP parser and then output to the client, where it will take over and output your HTML and run your JavaScript for you.

As long as both are valid when they run, they will work in the same HTML.

0

Short answer: Yes.

PHP is evaluated server side. When the browser gets the page, there is no PHP in it anymore. The page in the browser is the result of your PHP executing. The browser then loads that page and can run any JavaScript that is on it. The browser has no idea that PHP is involved at all.

PHP is server side, and JS is client side. They are totally separate and disconnected systems.

-2

Its not XHTML but make sure you wrap your script with HTML comments. Then your documents will validate.

<script>
   <!---
       javascript code
    -->
</script>
3
  • 2
    This hasn't been necessary for years. Commented Dec 2, 2011 at 18:55
  • I don't see how it's no longer a valid way of doing things. It does still work and the XHTML standard has not been changed. So if you look at my sentence, it starts with XHTML, the <!-- --> can still render a page valid, by blocking the JS out from the XHTML validator Commented Dec 2, 2011 at 20:57
  • That technique was originally used before XHTML, causing the javascript not to show in browsers that didn't support the script tag. (IE 1, Mosaic, etc.) Under an XML parser, using comments around your javascript will cause it to be treated as "not there at all". So it's unnecessary in current browsers and wrong for XML. Commented Dec 5, 2011 at 14:13

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.