0

In one PHP file I have a variable named $difficulty.

I need to access this file in my javascript file, game.js. I have tried this inside my game.js file:

userDif = "<?php echo json_encode($difficulty); ?>";
console.log("Difficulty " + userDif);

However, this does not work, it just prints out "<?php echo json_encode($difficulty); ?>"

I have also tried just:

userDif = <?php echo json_encode($difficulty); ?>;

But then you get an error as it doesn't expect "<"

Any help would be greatly appreciated.

Edit: Apologies: This has already been answered! I was just searching for the wrong thing. Sorry!

Choeeey
  • 1
  • 2
  • You're aware that PHP runs on the server, not "inside JavaScript", right? – Oliver Charlesworth Feb 15 '15 at 10:55
  • Your JS file doesn't seem to be executed as PHP on the server, it's just served as is. Can you rename it to game.php? – nnnnnn Feb 15 '15 at 10:55
  • 1
    PHP runs on the server, Javascript runs in the browser. Once the page has been sent to the browser, PHP is done. – Barmar Feb 15 '15 at 10:55
  • I don't understand how to handle it then? – Choeeey Feb 15 '15 at 11:00
  • @Choeeey either you hack it together by outputting the javascript code server side. Then you can at the same time output the data you need between the script tags. This is not really the way to do it though. What you usually want to do is make Javascript call the server side to get values. Look into "javascript ajax". – JimL Feb 15 '15 at 11:13

2 Answers2

0

Don't put quotes around the value. json_encode() will put quotes around the string, so you end up with extra quotes. It should be:

userDif = <?php echo json_encode($difficulty); ?>;
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I think you have something like this:

Php file

Js file included in php file

You have to run js code with php inside the php file, then you can use that variable inside the js file.

Php file:

<script type="text/javascript">
    var phpCode = "<?php echo 'hola'; ?>";
</script>
<script src="scriptFile.js" type="text/javascript"></script>

scriptFile.js:

alert(phpCode);
moonknight
  • 334
  • 1
  • 7
  • This does not work? It says phpCode is not defined in the js file – Choeeey Feb 15 '15 at 11:23
  • It works perfectly on my website. Be sure to include your script in the .php file (I wrote "scriptFile.js") and (obviously) be sure to use a .php file. – moonknight Feb 16 '15 at 15:15
  • Sorry, this did work, I made a silly mistake - I forgot to edit this to tell you so :) – Choeeey Feb 17 '15 at 16:06