Aryan G
Aryan G

Reputation: 1301

Is it possible to pass a php variable inside javascript?

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! :)

Upvotes: 4

Views: 429

Answers (4)

Arc
Arc

Reputation: 11296

Use json_encode() if your PHP has it.
This will automatically quote and escape your string and ensures that special characters are properly encoded to prevent cross-site scripting (XSS) attacks. However, I think you will have to pass UTF-8 strings to this function.

And vol7ron has a good point – you should put a semicolon ; after your statement and put a space between that and the question mark ? for better legibility.

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

You can also pass booleans, ints and even entire arrays to json_encode() to pass them to JavaScript.

Upvotes: 0

ndp
ndp

Reputation: 21996

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.

Upvotes: 1

Alex Pliutau
Alex Pliutau

Reputation: 21957

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

Upvotes: 2

Dies
Dies

Reputation: 149

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>

Upvotes: 2

Related Questions