I am somewhat new to JavaScript, and have been having an issue with a global variable. I have a group id that is part of my php session variables, that I want to place into a JavaScript global variable so that I can access the value in JavaScript. But JavaScript always shows the variable as undefined, so I must be doing somthing wrong. In a nutshell I have the following code:
<head>
<script type="text/javascript">var group = <?php echo($group)?>;</script>
</head>
<body>
<script type="text/javascript">
function clicked() {
alert(window.group);
}
</script>
When the alert window pops up it shows undefined, but I can tell by look at the source generated, as well as firebug that the value is being set to the variable at one point.
What am I doing wrong?
The best solution for this kind of problem is to always call
json_encodewhen printing a php variable as a JS variable. In your case, it would fail if your string contained a newline, or a quote