0

I am trying to write a game where you roll the dice and get half a quote and you have to guess if it matches the half that you were originally given. I am using AJAX and everything works fine right up until the end when I send a variable from php to javascript using

echo  '<script>currentQuote = $currentQuote;</script>'; 

It shows up on the page but when I check the value of currentQuote in JS it is undefined. Here is a link to a simplified version of the game just showing my problem.http://workwithu.com/Games/Game15snip.php The PHP code which you cannot see is:

<?php
$response = mt_rand(1,6);
echo $response;
$currentQuote=$response;
echo '<script>currentQuote = $currentQuote;</script>';//this not working
echo "<br>";
echo "currentQuote is:";
echo $currentQuote; //this shows on the screen fine
?>

Any help would be GREATLY appreciated. I have run out of ideas to try. Thanks

1

2 Answers 2

4

Basic PHP syntax. '-quoted strings do NOT interpolate variable values. If you do a view source on your page, you'll see a literal

<script>current Quote = $currentQuote</script>

in the page's source. Switch to a "-quoted string:

echo "<script>currentQuote = $currentQuote;</script>";//this not working
     ^---note                                       ^---note
Sign up to request clarification or add additional context in comments.

2 Comments

Also factor that $currentQuote may be a string, which could resolve to currentQuote = Some string that will break js; - btw I see it is a result of mt rand, but in general the comment is for anyone else, not you Marc B.
OK, I tried using double quotes and still got currentQuote=undefined. Maybe I should have mentioned that the PHP is coming from two files on the server via Ajax and I am trying to store what I get from the first response to pass via Javascript to the next file using Ajax.Maybe I can only use one PHP file and have to store all the values in there, but everything I read says that a variable can be stored with Javascript using <?php echo and although it show on the page it is not being stored so I can use it.
0

if you are using ' -Quoted sting you should use.

echo '<script>currentQuote = '.$currentQuote.';</script>';

or use " -quoted

echo "<script>currentQuote = $currentQuote;</script>";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.