Is it possible to pass php variable inside javascript?

I am trying to pass php variable inside javascript bt, it does not work.

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

Can this be done, or can I be somewhere incorrect ...

Thanks for your reply in advance! :)

+4
source share
4 answers

You are dynamically generating javascript. You will get rid of headaches, if you need it, make it simple. Transfer data from PHP to Javascript in the easiest way at the top of the page:

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

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

Now your inline code might be simpler:

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

A final recommendation would be to output this to your own function and use the onclick attribute.

+1
source

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

As for your question - PHP parses on the server side, and Javascript works on the client side. If you are not going to use AJAX and asynchronous calls, you can write the values ​​to the JS source, for example:

 <script type="text/javascript"> var foo = <?php echo $yourData; ?>; alert(foo); </script> 
+2
source
 <a href="javascript:wait1();getPass('<?=$current?>');">Comment</a> 
+2
source

Use json_encode() if your PHP has it.
This will automatically output a quote and run off your string and ensure that special characters are correctly 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 have to put a semicolon ; after your statement and put a space between this and the question mark ? for better readability.

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

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

0
source

All Articles