Skip to content Skip to sidebar Skip to footer

Embedding Javascript In Php

I would just like to get a simple explanation as how embedding javascript in php works and why we need to echo it out. I just need to understand the concept of embedding javascript

Solution 1:

It's like any other programming language - you can use only THAT particular programming language to accomplish something. e.g.

<?php$x = 42; // php variable assignment
alert($x); // javascript function call

This would never work. `alert() is a JS function which (usually) has no analog in PHP, therefore this would die with an undefined function error.

Since PHP can be embedded in other languages, and other languages can be "embedded" within PHP, you HAVE to have clear delimiters between the two, so the compilers can tell where one language ends and another starts. With php, that'd be accomplished by doing an "echo" of the JS code, or "breaking out" of PHP mode:

<?php$x = 42;
?>
alert(<?phpecho$x; ?>);

or

<?php$x = 42;
echo'alert(' . $x . ')';

What it boils down to is "context". If you're in PHP mode (e.g. within a <?php ... ?> block, you're writing PHP code, and any other language you use in there (html, JS) is just plain text as far as PHP is concerned.

If you're "out" of PHP mode, then you're in whatever language context the surrounding block is using.

<script>var x = 42;
   <?php// some php code here that causes output />
</script>

In the above case, your "context" is javascript - anything that the PHP causes to be output must be valid in the Javascript context it's embedded in.

so while

var x = <?phpecho42; ?>;

would work, because 42 is a valid bit of text to have in that particular spot, it would not be valid to have

var x = <?phpecho'</script>'; ?>;

That would produce the non-sensical

var x = </script>;

Solution 2:

JavaScript is client side, PHP is server side... Javascript can not be accessed by PHP.. You must use something like AJAX to pass back and fourth.. On the flip side, you can display PHP inside JavaScript.

<?$a = "25";
?><script>
alert(<?echo$a?>)
</script>

That works, but visa versa will not unless you use Ajax.

Solution 3:

You should make all justifiable attempts to separate languages whenever possible.

Just the same as any other data PHP parses it will only output what you tell it to. So if you don't tell PHP to send the data to the browser it wont send it.

With regard to language separation there are loads of PHP template engines out there that work out of the box to do this for you. You just need to work within their framework.

Post a Comment for "Embedding Javascript In Php"