2

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!

3
  • you need to send answer along with question from getQuestion.php Commented Nov 11, 2012 at 16:47
  • what js error you are getting Commented Nov 11, 2012 at 16:53
  • in the alert box I have: <?php echo $correctAnswer;?>; if I do not use quotes, the error is: Uncaught SyntaxError: Unexpected token ? Commented Nov 11, 2012 at 16:56

3 Answers 3

2

In your PHP inside while loop do this

$question=$row['description']."of ".$row['text']."?|".$row['answer'];
echo($question);

in your java script

if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var elements = xmlhttp.responseText.split("|");
       document.getElementById("question").innerHTML=elements[0];
       var rightAnswer = elements[1];
       alert(rightAnswer); 
    }

This is an idea. Change it to way that you want.

Sign up to request clarification or add additional context in comments.

Comments

1

Change Your javascript as:

Call it as responseXml:

<script type="text/javascript">
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)
        {
           xmlDoc=xmlhttp.responseXML; 
           document.getElementById("question").innerHTML=xmlDoc.getElementsByTagName('question')[0].firstChild.nodeValue;
           rightAnswer =xmlDoc.getElementsByTagName('answer')[0].firstChild.nodeValue;
           alert(rightAnswer); 
        }
    }
    xmlhttp.open("GET","getQuestion.php",true);
    xmlhttp.send();
 }

 </script>

Change Your php file as:

<?php
 header('Content-Type: text/xml');
 header ('Cache-Control: no-cache');
 header ('Cache-Control: no-store' , false);     // false => this header not override the previous similar header

$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);
} 


$xmlStr='<?xml version="1.0" encoding="UTF-8"?>
<data>
   <question>'.$question.'</question>
   <answer>'.$correctAnswer.'</answer>
</data>
';
echo $xmlStr;
?>

6 Comments

I have the error: Uncaught TypeError: Cannot call method 'getElementsByTagName' of null, in this line: document.getElementById("question").innerHTML=xmlDoc.getElementsByTagName('question')[0].firstChild.nodeValue;
How can I fix the problem? I like the idea of using XML, but I am pretty new using it.
I know, but why I have that error? I upvoted your answer. It seems to be very elegant, but I really want to make it to work :)
Please now check the updated code for php file.do not forget to put connection in your php file.also there should be no extra space in it.
in JavaScript I only added the code for if() condition, and in php file I added 3 'header' lines and $xmlStr=... and echo $xmlStr. I also added mysql_close($con); before I closed php tag. Can I place header lines wherever in php code, or should be the first 3 lines of my php code?
|
0

when you have Javascript and PHP on the same page, then you can pass data to the javascript using json_encode:

<?php
$var = 'hello';
?>
<script type="text/javascript">
var v = <?= json_encode($var); ?>;
</script>

without quotes

if you make an ajax call - the variable is not passed through the PHP, but as an http request. You use plain JS in that case

1 Comment

in your case - there's no php with the javascript. only plain JS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.