I want to pass a php variable into JavaScript. I have to get from a database the questions(randomly, one by one) and if the end user responses correctly,
the program is doing something else.
database
+------+-----------------------+---------------+-----------------+
| q_id | description | text | answer |
+------+-----------------------+---------------+-----------------+
| 1 |What is the capital | United States | Washington D.C. |
| 2 |What is the capital | California | Sacramento |
| 3 |What is the capital | Maryland | Annapolis |
+------+-----------------------+---------------+-----------------+
In the php file, variables $question and $correctAnswer have the following values:
php code:
$sql="SELECT description, text, answer FROM Questions";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$question=$row['description']."of ".$row['text']."?";
echo($question);
$correctAnswer=$row['answer'];
//echo($correctAnswer);
}
javascript code:
var rightAnswer;
function takeQuestion()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("question").innerHTML=xmlhttp.responseText;
rightAnswer ='<?php echo $correctAnswer;?>';
alert(rightAnswer);
}
}
xmlhttp.open("GET","getQuestion.php",true);
xmlhttp.send();
}
The program is printing randomly the questions, but I have problems passing the variable
$correctAnswer to Javascript. Variable rightAnswer in JavasScript should take the value
of php variable $correctAnswer. Any help will be appreciated. Thank you in advance!
In your PHP inside while loop do this
in your java script
This is an idea. Change it to way that you want.