I'm new to to working with php html and javascript so I apologize if this question is bad but whenever I add this variable that echos php I can no longer advance the program to the next window. The only thing I can think of is that the next window is a html and not a php file. Would that be the reason or am I doing something else wrong? Thanks!
<script>
var winner = <?php echo $winnerName ?>;
//Creates random num for winner base on num of members.
function changeNum() {
//Num of members.
num = document.getElementById("num").value;
//winner.
num2 = Math.round((Math.random() * (num - 1) + 1));
//Storage to second page
localStorage.setItem("winner", num2);
localStorage.setItem("name", winner);
window.location = "second_page.html";
}
</script>
PHP will print out your string in plain text and to the browser it will exactly like if you were to have typed and hardcoded the string held by $winnerName
in the file itself.
For example if $winnerName = 'Bob'
the browser will see var winner = Bob;
and complain that you haven't defined the variable Bob
.
Keeping that in mind, there are two methods to make javascript treat your string as a string, and not a variable.
var winner = <?php print json_decode($winnerName); ?>;
var winner = '<?php print $winnerName; ?>'
Both of which will display to the browser var winner = 'Bob'
.
A couple of potential issues:
$winnerName
is probably a string, which means that you need to wrap it in quotes: '<?=$winnerName;?>'
(and probably escape it as well to be on the safe side): '<?=addslashes($winnerName);?>'
Make sure that num
is a legitimate integer: parseInt(document.getElementById("num").value)
just in case that might be throwing an error.
Also, you'll want to look at your console to see what javascript error is being throw - it will narrow down the issue for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.