Matt Steadman
Matt Steadman

Reputation: 77

JavaScript global variable undefined issue

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?

Upvotes: 2

Views: 715

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92284

The best solution for this kind of problem is to always call json_encode when printing a php variable as a JS variable. In your case, it would fail if your string contained a newline, or a quote

<script type="text/javascript">var group = <?php echo(json_encode($group)) ?>;</script>

Upvotes: 1

craigb
craigb

Reputation: 16907

If the result of <?php echo($group) ?> is a string then you'll need to put quotes in the script source like so:

<script type="text/javascript">var group = '<?php echo($group)';</script>

You don't need to use window.group to assign it as that is already the context of the variable.

Upvotes: 0

ValeriiVasin
ValeriiVasin

Reputation: 8706

use:

<script type="text/javascript">window.group = <?php echo($group)?>;</script>

Upvotes: 0

Related Questions