...

View Full Version : store data when using hidden div's for my quiz



Rangers
03-09-2011, 02:43 PM
Old Pedant help me create a quiz in JavaScript and CSS which uses hidden DIV’s. Question 1 will be visible until a user answers the question then clicks submit. The second question will then be visible and the first will disappear and so on. My question is, since there is only 1 text box that gets used for multiple questions, how can I insert the results into my MySql database?
Here is some on the code in case you need to look in order to understand how my quiz works.



function Question( q, mina, a )
{
this.query = q;
this.minAnswer = mina;
this.answer = a;
}

var Questions = [
new Question('What movie did Michael Eisner say was his "market research" <br/> for Disneys NHL entry',
'ducks', 'The Mighty Ducks'),
new Question('What was the only team to win two World Series in the 1980s',
'dodgers', 'The Los Angeles Dodgers'),
new Question('What U.S. college sport honors its best player with the Hobey Baker Award? ',
'hockey', 'Hockey'),
new Question('What essential do track racing bicycles lack that a recreational<br/>rider wouldnt be caught dead without',
'breaks', 'Breaks'),
new Question('Who, along with the Montreal Canadians, are the only founding<br/>members of the NHL remaining',
'leafs', 'Toronto Maple Leafs'),
new Question('What U.S. college sport honors its best player with the Hobey Baker Award? ',
'hockey', 'Hockey'),
new Question('In the Einsteins Theory of Relativity,<br/>E=mc2, what does c stand for',
'light', 'The Speed of Light' )


];

var qNumber = -1;
var ticker = null;

function nextQuestion( )
{
++qNumber;
if ( qNumber >= Questions.length )
{
alert("Done");
return;
}
var curq = Questions[qNumber];
document.getElementById("ShowQuestion").innerHTML = curq.query + "?";
document.QForm.CheckAnswer.style.backgroundColor = "lightgreen";
document.QForm.answer.value = "";
timeleft = 31;
tick();
}


Html


<body onload="nextQuestion()">
<div id="ShowQuestion"></div>
<form name="QForm">
Your answer: <input name="answer" class="answer" /><br/><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" name="CheckAnswer" class="answerButton" onclick="check()" />
</form>
</body>
</html>

Fumigator
03-09-2011, 02:55 PM
You have your assignment, Old Pedant, now hop to it! :rolleyes:

Old Pedant
03-10-2011, 01:11 AM
Add hidden form fields to your <form>:



<input type="hidden" name="ans0" />
<input type="hidden" name="ans1" />
...
<input type="hidden" name="ans9" />


And then this is the code for the check() function that is in the <input type="button">:



function check( )
{
var form = document.QForm;
form["ans" + qNum ].value = form.answer.value;
nextQuestion( );
if ( qNumber >= Questions.length ) form.submit(); // submit answers to server
}

(You can combine that with other code in existing check() or just do all answer validation on the server.)

On the server, you use ask for answers "ans0" through "ans9" (or whatever your range is).

************




new Question('What essential do track racing bicycles lack that a recreational<br/>rider wouldnt be caught dead without',
'breaks', 'Breaks'),

No, I think that track racing enthusiasts need all the breaks they can get!

On the other hand, they don't use brakes.

Old Pedant
03-10-2011, 01:12 AM
By the by, if you had said that you would be using server-side code with this and storing the answers, I'd probably have done the whole thing in a completely different way.

Rangers
03-10-2011, 06:00 PM
Would it look something like this?



<body onload="nextQuestion()">
<div id="ShowQuestion"></div>
<form name="QForm">
<input type="hidden" name="q1" />
<input type="hidden" name="q2" />
<input type="hidden" name="q3" />
<input type="hidden" name="q4" />
<input type="hidden" name="q5" />
<input type="hidden" name="q6" />
<input type="hidden" name="q7" />
Your answer: <input name="answer" class="answer" /><br/><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" name="CheckAnswer" class="answerButton" onclick="check()" />
</form>

and the check function


function check( )
{
clearTimeout(ticker);
var form = document.QForm;
var curq = Questions[qNumber];
var okay = form.answer.value.toLowerCase().indexOf(curq.minAnswer) >= 0;
if ( okay )
{
alert("Correct!");
} else {
alert( ( timeleft <= 0 ? "Time is up!" : "Incorrect." )
+ "\nThe correct answer is:\n" + curq.answer );
}
form["q" + qNum ].value = form.answer.value;
nextQuestion();
if ( qNumber >= Questions.length ) form.submit(); // submit answers to server


Right now when I hit the submit button it will stop the clock and not go to the next quetion.

Also, can someone move this to the JavaScript forum?

Thanks for looking

Old Pedant
03-10-2011, 07:36 PM
Looks right to me.

But you don't have a SUBMIT button; you just have a button.

Rangers
03-10-2011, 08:04 PM
Looks right to me.

But you don't have a SUBMIT button; you just have a button.

Thanks, that worked, however, the issue now is that it will repeat the same question rather than going to question 2. Any ideas?

Old Pedant
03-10-2011, 08:37 PM
I don't see why, since you are invoking nextQuestion.

Can you put this up live someplace to look at?

Rangers
03-10-2011, 09:15 PM
Can you put this up live someplace to look at?

Sure,

http://joe.peanutspace.com/trivia/sports2.html

If you answer the question and click submit, you will get the prompt either stating that you answered correctly or incorrectly. After you hit okay it will reload the same question over and restart the timer rather than going to q2.

Old Pedant
03-10-2011, 10:00 PM
You made a handful of goofs.

First of all, you changed the type="button" to type="submit"

That was a *HUGE* mistake!

Every time a person hit the now-submit button, it SUBMITS THE FORM which STARTS THE PAGE ALL OVER!

Secondly, you used qNum where you needed to use qNumber

BE CONSISTENT!

Finally, you named your hidden fields q1 to q7. Can't be. Have to be q0 to q6.

Or change the JS code to account for the difference.

So:


function check( )
{
clearTimeout(ticker);
var form = document.QForm;
var curq = Questions[qNumber];
var okay = form.answer.value.toLowerCase().indexOf(curq.minAnswer) >= 0;
if ( okay )
{
alert("Correct!");
} else {
alert( ( timeleft <= 0 ? "Time is up!" : "Incorrect." )
+ "\nThe correct answer is:\n" + curq.answer );
}
form["q" + qNumber ].value = form.answer.value;
nextQuestion(); // this needs to be *BEFORE* the IF test!!!
if ( qNumber >= Questions.length ) form.submit(); // submit answers to server
}


and



<input type="hidden" name="q0" />
<input type="hidden" name="q1" />
<input type="hidden" name="q2" />
<input type="hidden" name="q3" />
<input type="hidden" name="q4" />
<input type="hidden" name="q5" />
<input type="hidden" name="q6" />
...
<input type="button" value="Submit" name="CheckAnswer" class="answerButton" onclick="check()" />

Old Pedant
03-10-2011, 10:01 PM
If you need the hidden fields to be numbered starting at 1, then change the JS from


form["q" + qNumber ].value = form.answer.value;

to


form["q" + (qNumber + 1) ].value = form.answer.value;

Rangers
03-11-2011, 12:17 AM
Thanks, That worked.

Now I am having trouble getting the data to show in the MySql database. Right now it is just showing blank spaces. Here is my code with the sql in it.



<html>
<head>
<style type="text/css">
div#ShowQuestion {
width: 500px;
padding: 8px;
border: solid blue 1px;
background-color: lightblue;
color: blue;
}
.answer {
width: 200px;
}
.answerButton {
width: 200px;
background-color: lightgreen;
border: solid black 2px;
}
</style>
<script type="text/javascript">

function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}

document.onkeypress = stopRKey;





function Question( q, mina, a )
{
this.query = q;
this.minAnswer = mina;
this.answer = a;
}

var Questions = [
new Question('What movie did Michael Eisner say was his "market research" <br/> for Disneys NHL entry',
'ducks', 'The Mighty Ducks'),
new Question('What was the only team to win two World Series in the 1980s',
'dodgers', 'The Los Angeles Dodgers'),
new Question('What U.S. college sport honors its best player with the Hobey Baker Award? ',
'hockey', 'Hockey'),
new Question('What essential do track racing bicycles lack that a recreational<br/>rider wouldnt be caught dead without',
'brakes', 'Brakes'),
new Question('Who, along with the Montreal Canadians, are the only founding<br/>members of the NHL remaining',
'leafs', 'Toronto Maple Leafs'),
new Question('What U.S. college sport honors its best player with the Hobey Baker Award? ',
'hockey', 'Hockey'),
new Question('In the Einsteins Theory of Relativity,<br/>E=mc2, what does c stand for',
'light', 'The Speed of Light' )


];

var qNumber = -1;
var ticker = null;

function nextQuestion( )
{
++qNumber;
if ( qNumber >= Questions.length )
{
alert("Done");
return;
}
var curq = Questions[qNumber];
document.getElementById("ShowQuestion").innerHTML = curq.query + "?";
document.QForm.CheckAnswer.style.backgroundColor = "lightgreen";
document.QForm.answer.value = "";
timeleft = 31;
tick();
}

function tick( )
{
--timeleft;
var btn = document.QForm.CheckAnswer;
if ( timeleft < 10 ) btn.style.backgroundColor = "pink";
btn.value = timeleft + " seconds";
if ( timeleft <= 0 )
{
check();
return;
}
ticker = setTimeout( tick, 1000 );
}

function check( )
{
clearTimeout(ticker);
var form = document.QForm;
var curq = Questions[qNumber];
var okay = form.answer.value.toLowerCase().indexOf(curq.minAnswer) >= 0;
if ( okay )
{
alert("Correct!");
} else {
alert( ( timeleft <= 0 ? "Time is up!" : "Incorrect." )
+ "\nThe correct answer is:\n" + curq.answer );
}
form["q" + (qNumber + 1) ].value = form.answer.value;
nextQuestion(); // this needs to be *BEFORE* the IF test!!!
if ( qNumber >= Questions.length ) form.submit(); // submit answers to server
}
</script>

<?php

$con = mysql_connect("localhost","root","password");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

mysql_select_db("trivia", $con);



$sql="INSERT INTO sports_trivia (q1, q2, q3, q4, q5, q6, q7)

VALUES

('$_POST[q1]', '$_POST[q2]', '$_POST[q3]', '$_POST[q4]', '$_POST[q5]', '$_POST[q6]', '$_POST[q7]')";



if (!mysql_query($sql,$con))

{

die('Error: ' . mysql_error());

}

mysql_close($con)

?>

<body onload="nextQuestion()">
<div id="ShowQuestion"></div>
<form name="QForm">
<input type="hidden" name="q1" />
<input type="hidden" name="q2" />
<input type="hidden" name="q3" />
<input type="hidden" name="q4" />
<input type="hidden" name="q5" />
<input type="hidden" name="q6" />
<input type="hidden" name="q7" />
Your answer: <input name="answer" class="answer" /><br/><br/>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="Submit" name="CheckAnswer" class="answerButton" onclick="check()" />
</form>
</body>
</html>


Here is what my database looks like


+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | mediumint(9)| NO | PRI| NULL | auto_increment |
| fn | varchar(15) | YES | | NULL | |
| ln | varchar(15) | YES | | NULL | |
| q1 | varchar(30) | YES | | NULL | |
| q2 | varchar(30) | YES | | NULL | |
| q3 | varchar(30) | YES | | NULL | |
| q4 | varchar(30) | YES | | NULL | |
| q5 | varchar(30) | YES | | NULL | |
| q6 | varchar(30) | YES | | NULL | |
| q7 | varchar(30) | YES | | NULL | |
| q8 | varchar(30) | YES | | NULL | |
| q9 | varchar(30) | YES | | NULL | |
| q10 | varchar(30) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+

Old Pedant
03-11-2011, 01:35 AM
You only want to put the data into the db *AFTER* the <form> has been filled in!!!!

So you should either have the INSERT code in a different PHP page than the quiz or you should be looking for some "trigger" from the <form> to tell you that it's time to insert data.

I use a "trigger", usually like this:


<form ...>
<input type="hidden" name="POSTBACK" value="YES" />
...

And then my PHP code would do this:


<?php

if ( $_POST["POSTBACK"] == "YES" )
{
... here is the code to do the the INSERT into the db ...
}

?>

Well, actually, I don't use PHP, but that's what it would look like if I did.

BUT...

But remember that if you do this, then after inserting the data into the DB the quiz will show up again in the browser.

That's *PROBABLY* not what you want. You probably just want a "thank you" message or some such.

So the easy answer to that is to do


<form action="processAnswsers.php" method="post">

and then just put your DB INSERT code into "processAnswers.php" and *NOT* into the <form> page!

Rangers
03-11-2011, 07:42 PM
So the easy answer to that is to do


<form action="processAnswsers.php" method="post">

and then just put your DB INSERT code into "processAnswers.php" and *NOT* into the <form> page!

Perfect. Thank you for the useful advice. This did the trick! :thumbsup:

Rangers
03-14-2011, 01:06 AM
I have one last issue.

I have 4 webpages

1. index.html which asks the user for their First and Last name which goes into the database when a user clicks submit.

2. cat1.php has the PHP code that enters in the information from index.html (this pages is also a redirect page so it will tell you about the quiz and automatically redirect you to the beginning of the quiz)

3. sportsquiz.html which has the quiz questions.

4. process.php which inserts the data from the quiz into the database.

What is happening now is that the data from index.html and the data from sportsquiz.html is going on separate lines in the db (which makes sense since data is being sent to the db at separate times) below is an example

http://www.joe.peanutspace.com/trivia/Picture 16.png

So the question is: What is the best way to submit the data so that the results are on the same line or part of the same id number?

I was reading about PHP sessions. has anyone ever used PHP sessions? It seems like I can use a PHP session so I can store the data until the last page and submit all the data at once, however, I was not successful so if anyone can show me an example I would greatly appreciate it!

Rangers
03-14-2011, 01:24 AM
http://joe.peanutspace.com/trivia/

Here is the website live so you can see the structure.

Old Pedant
03-14-2011, 02:33 AM
Pass the name in hidden form fields.

If somebody doesn't answer the questions--just leaves the site--why record their name in the DB in the first place?

So you can get rid of your 2nd page, entirely.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum