I wanted to use a session variable in a javascript function. How are they combined? The idea is that in a quiz question and answer application. I have the response in the session variable (php), and when the user presses the button, I want a javascript function to check it.
I wanted to know how to introduce inside a function, specifically in an IF, to be able to compare a VALUE with a session variable.
Example (approximate):
<script language="javascript">
function comprobar(){
var respuestaUsuario = document.getElementsById("boton").value;
if(respuestaUsuario == $_SESSION['respuestaCorrecta']){
alert("Respuesta Correcta")
}
}
</script>
<button id=boton name=boton value="a" onclick="comprobar()">
Thank you!
You can do this by opening and closing curly braces directly in your js, like so: (this text editor doesn't allow opening curly braces from php):
or you can use a print_r, json_encode,... or whatever you see, whatever is most comfortable or useful for you. This will also depend on how your variable is (string, array, json,...).
However, I think it is a best practice that you do the following:
Include your variable in a hidden input:
And now fetch the value in js: