Taylor maddox Taylor maddox - 4 months ago 5x
PHP Question

JavaScript with php variabe isn't working

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!

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;
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";


A couple of potential issues:

  1. $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);?>'

  2. 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.