Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

This question already has an answer here:

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..

share|improve this question

marked as duplicate by Pragnesh Chauhan, rink.attendant.6, Hanky 웃 Panky, Qantas 94 Heavy, Krishnabhadra Nov 1 '13 at 9:03

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.

    
use ajax to send javascript variable to server. –  Ajeet Sinha Nov 1 '13 at 4:03
    
no . im using to alert it .. –  Vincent Nov 1 '13 at 4:12

2 Answers 2

up vote 1 down vote accepted

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

<script>
    var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
share|improve this answer
    
what if the variable in php is a database array. should i do this? var myvar = new Array(); myvar = <?php echo json_encode($myVarValue); ?>; is this right? –  Vincent Nov 1 '13 at 4:11
1  
Try to alert the array as alert(<?php echo json_encode($myVarValue); ?>); –  Jenz Nov 1 '13 at 4:15

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.

share|improve this answer
    
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 <div><script></script><?php?></div> .. the php refreshes and change it's value. but the the value in javascript doesnt change. oh no... what should i do... –  Vincent Nov 2 '13 at 1:38

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