September 10, 2013

Is it a good practice to use php code inside javascript?

Nabeel Sheikh’s Question:

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 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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!