I heard lot of experts saying entering php code inside javascript is not a good practice. I wanted to know if it's true. If yes, then will it effect the performance? or is there any other reasons?
For example:
<?php
$num=1;
?>
<script>
var x = "<?php echo $num;?>";
</script>
No, it is not good practice.
will it effect the performance?
I do not specifically know which performance you meant when you wrote that line, but about all performances I can imagine, I would say: Most certainly, no.
is there any other reasons?
Mixing two languages is hard as it requires proper encoding. This makes things complex. Complexity is bad practice.
Typically, it is bad practice to use language X to generate code in language Y.
Try decoupling the two languages by making data their only interface -- don't mingle the code.
In your example, you could improve the code by using PHP to populate a cfg structure that's available to JavaScript:
NO it will not effect the performance, but it affects manageability and security.
In your case, can your javascript function without knowing the value of num
? or Are you just developing the JS script from PHP? Latter is the use you should avoid.
Lets take an example where num
was used to know the number of items in shopping cart. Now thats a very vital piece of information, but since its JS, it can easily be manipulated. In such case, you should store such sensitive information on the server and not on the client.
A few points:
Normally, I declare a global config object and pull it through a separate ajax request when the page loads (This can be a PHP script echoing JSON).
MyApp : {
x: '123',
y: 'xxx'
}
and then access it from my javascript files later:
(function(){
alert(MyApp.x)
})();
I dont think this a bad practice, if the values are dynamic, you can just do as,
test.php
<script type="text/javascript">
var foo = '<?php echo $foo;?>';
</script>
<script type="text/javascript" src="test.js"></script>
test.js
$(function(){
alert(foo);
});
If it is not dynamic values, recommends no need to use php tags
I don't think it is that bad. Assign your dynamic PHP values to a JavaScript variable in your PHP templates(as first line if possible) and then call these variables inside your external JavaScript files. And I fully agree with @hakre answer.