Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)
Access a JavaScript variable from PHP

I have a Javascript function that takes in one variable. The function has some php code inside it. I want to use this variable inside the php section of the function. I couldn't get it to work. How is it done?

share|improve this question
1  
No-can-do, boss, at least not the way I think you're thinking :-) The PHP is being interpreted on the server before it's sent to the client. You can use PHP to populate a javascript variable directly, but going the other direction requires some kind of AJAX post. – rjz Mar 5 '12 at 5:56
this type of question is all over the web, please google it first – t q Mar 5 '12 at 5:58
you want JS inside php or php inside JS ? – Sam Arul Raj Mar 5 '12 at 6:21

marked as duplicate by Amber, roXon, casperOne Mar 6 '12 at 19:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

The issue is that your PHP code is being rendered on the server before being served to the client. I would recommend either converting the PHP code into Javascript code or creating an AJAX call to the PHP function.

share|improve this answer

Start reading about AJAX! You will likely need to rewrite some of the code you have written but what you are attempting to accomplish is not really possible otherwise.

share|improve this answer
How easy is it to do with AJAX? – node ninja Mar 6 '12 at 20:49
It is simple once you get used to it, you will definitely need to do some reading and learning but it is fairly simplistic once you have done it a few times. – Ryan Kempt Mar 6 '12 at 21:01

try with it

<script>
    var whatever = "<?php echo $phpVar ?>";
</script>
share|improve this answer
this way is not correct – Sam Arul Raj Mar 5 '12 at 6:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.