Thursday, January 19, 2012

Passing variables from PHP to JavaScript


There is a bug in the following code when passing variables from PHP to Javascript:
 <script type="text/javascript">
<!--//--><![CDATA[//><!--
var question_type = <?php echo("bbb1"); ?>;
alert(question_type);
//--><!]]>
</script>
When running this code, no alert box is shown. In FireFox, selecting web developer then choose Error Console in the top menu, the error is  "bbb1 is not defined."
The above code is equivalent to
var question_type= bbb1;
The correct syntax should be:
 var question_type= "bbb1";
(The problem is due to string, number is OK)
The final correct code should be:
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var question_type = "<?php echo("bbb1"); ?>";
alert(question_type);
//--><!]]>
</script>

No comments:

Post a Comment