Reading the Javascript Variables in PHP: A Common Mistake by Developers

Javascript gets executed on client side and PHP on the server side. Most of web developers will be aware of this fact. But when asked a question how would you be reading a javascript variable value into PHP, the reply from many would be to do it this way:
$total = "<script language=javascript>document.write(subtotal);</script>";
which looks valid and infact a code like the would definitely work
<script type="text/javascript">
var subtotal=100;
</script>
<?php
$total = "<script language=javascript>document.write(subtotal);</script>";
echo "Total1: $total<br>";
?>
Yes this code works as expected, actual problem is when user tries to go ahead and use this variable further in the code. For example:
<script type="text/javascript">
var subtotal=100;
</script>
<?php
$total = "<script language=javascript>document.write(subtotal);</script>";
echo "Total1: $total<br>";
$total=$total+10;
echo "Total2:$total<br>";
?>
Now just guess the output of this program. Wanna know if your guess is right or not just check here. How many of you guessed it would be
Total1:100
Total2:110
This will not be what is printed in the browser because $total = "<script language=javascript>document.write(subtotal);</script>"; does not actually set value of $total to value of javascript variable total, it is set to the string and browser just changes that string to actual value (i,e a javascript execution). This looks like very basic things but some developers do write thi kind of code. Better way is to save such javascript variables as part of cookie and use it on subsequent PHP code.


No comments:

Post a Comment