Jump to content

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.

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.