tags:

views:

106

answers:

4

Hello everyone,

I am trying to pass a php variable inside javascript bt it is not working.

<a href="javascript:wait1();getPass('<?php echo $current?>');">Comment</a>

Is it possible to do so or I may be incorrect somewhere...

Thanks for your response in advance! :)

+2  A: 

First of all, you probably should change 'java' tag to 'javascript'.

Regarding your question - PHP is parsed on the server side, while Javascript runs on the client side. If you are not going to use AJAX and asynchronous calls, you could write values to the JS source, like this:

<script type="text/javascript">
  var foo = <?php echo $yourData; ?>;
  alert(foo);
</script>
Dies
actually, I am using AJAX.... so, sticked with the problem.
Anjali
A: 
Archimedix
pretty sure the `?` *won't* be interpreted as an operator.
Mark
Thanks ! I couldn't observe that either with my version of PHP but was not sure. Removed that part.
Archimedix
+2  A: 
<a href="javascript:wait1();getPass('<?=$current?>');">Comment</a>
Alexander.Plutov
+1  A: 

You're dynamically generating Javascript. You will save yourself some headaches if when you need to do this you, keep it simple. Transfer the data from PHP to Javascript in the simplest way possible at the top of the page:

<script type="text/javascript" >
var $current = '<%? echo $current; %>';
</script>

As others have pointed out, you will want to encode and quote your php variable, using json_encode (in which case you probably won't need the quotes), or a simpler escape function if you know the possible values.

Now, your inline code can be simpler:

<a href="javascript:wait1();getPass($current);">Comment</a>

A final recommendation would be to pull this out into its own function, and use the "onclick" attribute.

ndp