1

i know this is too dumb to ask. but i'll still ask this question..

i know how to pass the php variable to javascript variable inside the javascript function

function foo(){
var bar = <?php echo $foo; ?>
}

But how about from php variable to javascript inside a javascript function.

function foo(){
var bar;
<?php echo $foo; > = bar;
}

is this correct? because my javascript function is not working..

Vincent
  • 852
  • 6
  • 29
  • 67

2 Answers2

1

If you do want to use PHP, always encode with json_encode before outputting.

<script>
    var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Jenz
  • 8,280
  • 7
  • 44
  • 77
0

What you're trying to do is not possible. Remember that PHP runs on the server and renders the page to the browser. Only after the browser has received the finished PHP output does any Javascript on the page execute.

To pass JS variables into PHP you have to send them back to a script on the server using AJAX, and then do something in JS with the PHP result.

joshstrike
  • 1,753
  • 11
  • 15
  • oh. now i understand why everytime i send a data to the server using php. the value(php variable) in my javascript doesnt change. im having a little problem here. like passing a value using only a div. after that. the div will refresh. that div has a script inside. like
    .. the php refreshes and change it's value. but the the value in javascript doesnt change. oh no... what should i do...
    – Vincent Nov 02 '13 at 01:38