0

I want to be able to pass variables from php into my javascript code in order to save a given users high score. I have done that successfully by at the top of my page by declaring:

<?php
    session_start();


    $bricks = $_SESSION["bricks"];
    require 'includes/dbh.inc.php';
    require 'save.php';


?>

SESSION['bricks'] is the high-score in the database. A the end of of the html code within the php code I have my entire game written within a script tag. In the game

this.highScore = "<?php echo $bricks?>";

But this is long and messy. Lets say I wanted to replace the long script tag with a <script src="myGame.js"></script> this would be problematic because the file would no longer be a php file and would not be able to grab the session variable bricks.

When using the global scope I can grab the variable highscore from the session variable

<script> var highScore = <?php echo $bricks;?>;</script>

then later:

<script>console.log(highScore)</script>

but if I make the second script tag link to a source:

<script src="myGame.js"></script>

I will not be able to access that variable highScore in myGame.js. Is there a way to pass a variable from a script tag at the top of your page into a script tag with an src attribute and access that variable within the javascript document that is linked? there is a workaround, but I want to know if I can make it more manageable this way.

1
  • “this would be problematic because the file would no longer be a php file” - well then make it one. myGame.php, make it output the correct Content-Type header for a JavaScript resource first, and then the actual JS code - created dynamically, however you like … stackoverflow.com/questions/531311/… Commented Mar 31, 2020 at 13:04

1 Answer 1

1

First make your js code stable:

var highScore = parseInt("<?php echo $bricks;?>");

In your javascript object try set global variable highScore to object's property :

this.highScore = highScore;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.