Jump to content

Can I pass PHP variables content to Javascript?


YigalB

Recommended Posts

I wrote a short quiz in which PHP code creates a mathematical question based on random parameters.

The intention was to let JS to check the user's answers (via form) and compare it to the required results.

 

How can I pass the required data from PHP to the JS? After all, PHP variables are not recognized by the client side when executing the JS.

 

 

I haven't done anything like that but I have added picture info to js. I did it just like it was html

 

<div id="loadarea">

</div>

 

while {

echo '<a href=".$variable." rel="enlargeimage"  rev="targetdiv:loadarea, trigger:click" title="'.$row['pic_info'].'" >';

}

 

It uses a loop and loads the last eight pics and displays in loadarea.

 

 

 

You can simply eval the equation.

 

<script type="text/javascript">
function check() {
	var question = document.getElementById('question').innerHTML;
	var answer = eval(question);
	var input = document.getElementById('answer').value;
	var message = '';
	if( answer == input ) {
		message = 'Correct';
	} else {
		message = 'Incorrect';
	}
	document.getElementById('message').innerHTML = message;
}
</script>

Please answer the following: <span id="question">6+7</span> = <input type="text" name="answer" id="answer"><br>
<input type="button" value="Check" onclick="check()"><br>
<span id="message"></span>

 

I'm not sure of the security issue of using eval in JavaScript. I don't image it's too bad, as any manipulation of the DOM by an attacker makes the usage of eval trivial.

You might want to look into Json encoding your 'answers' array (if indeed that is what you have). Then you can set that string as a javascript var and parse it to retrieve an object of 'keys and values'. Then you can do with it as you like in your javascript to check the answers for each question.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.