Convert PHP String to JavaScript String
How good is the normal method for converting PHP strings to JavaScript strings? The code below shows you that with JSON, it's a cinch. Without it—forget it (unless you are willing to settle for a really crude method). This method is good for numbers but not strings: var temp = <?php echo $temp; ?>;</b>
<HTML>
<HEAD>
</HEAD>
<body>
<?php
$temperatures="hot";
echo "Convert PHP String to JavaScript String";
echo "<br><br>";
echo "PHP string value";
echo "<br><br>";
echo $temperatures;
$temp_hotter="now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party now is the time for all good men to come to the aid of the party";
echo "<br><br>";
echo "PHP string value";
echo "<br><br>";
echo $temp_hotter;
?>
<script language="javascript">
var temperatures = <?php echo json_encode($temperatures); ?>;
var temp_hotter = <?php echo json_encode($temp_hotter); ?>;
alert("JavaScript string values: "+temperatures+" \n\n"+temp_hotter);
document.write("<br><br><br>But if you try to declare this string in PHP:<br><br><b>$temp=\"cold\";</b><br><br>and convert it in JavaScript with:<br><br><b>var temp = <?php echo $temp; ?>;</b><br><br> ............. IT WON'T WORK, AND NEITHER WILL ANY OTHER STRINGS WITHOUT JSON!");
</script>
</body>
</html>