I am facing a little js/php issue. I have 2 different files (a .php one and a .js one containing some scripts the .php page will execute). I would like to send a php variable to the .js page. I looked over the internet but did not find anything that could help me... Thanks for your help !
            
        
            
3
	
        
            
        
    
- 
        need more info. Where and how is the JS executed? When do you need to send the variable?MightyPork– MightyPork2014-07-11 09:51:03 +00:00Commented Jul 11, 2014 at 9:51
- 
        What is a .js page? Is this an HTML document generated from Node.js or something?Quentin– Quentin2014-07-11 09:52:04 +00:00Commented Jul 11, 2014 at 9:52
- 
        A js page is a Javscript page. The script is executed when the user clicks on a link (in the .php page). At this very moment, i need to send the .js page the variable.rocketer– rocketer2014-07-11 09:54:51 +00:00Commented Jul 11, 2014 at 9:54
                    
                        Add a comment
                    
                 | 
            
                
            
        
         
    3 Answers
One solution is to define a JS variable in the HTML (produced by your PHP script):
<script type="text/javascript">
    var SOME_VAR = <?= json_encode($myvariable) ?>;
</script>
I'm using json_encode(), since it will add quotes around strings, and write arrays etc so that it's valid JavaScript.
After that, link the external JS file, in which you can use SOME_VAR with the value that came from PHP.
1 Comment
sumit
 i deleted my answer .. stackoverflow is too fast :) .. also one upvote
  You can try to embed the php variable in an hidden input field and try to access that input field in javascript.
 <input type = "hidden" id = "phpvar" value <?php echo $hiddenVar; ?> />
  in javascript 
 var hiddenPhpVar = document.getElementById('phpvar').value;
1 Comment
MightyPork
 input outside form is not valid, if I'm not mistaken.
  
