0

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? Commented Jul 11, 2014 at 9:51
  • What is a .js page? Is this an HTML document generated from Node.js or something? Commented 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. Commented Jul 11, 2014 at 9:54

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i deleted my answer .. stackoverflow is too fast :) .. also one upvote
0

You can't send php variable directly to js file. For this purpose you have to write php value in a hidden or text field then get that value in js.

Comments

-1

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

input outside form is not valid, if I'm not mistaken.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.