Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    New Coder
    Join Date
    Oct 2010
    Location
    Denver
    Posts
    26
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Question store data when using hidden div's for my quiz

    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.

    Code:
    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
    Code:
    <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>
    Last edited by Rangers; 03-09-2011 at 02:47 PM.

  • #2
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    You have your assignment, Old Pedant, now hop to it!

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,171
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    Add hidden form fields to your <form>:

    Code:
    <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">:

    Code:
    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).

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

    Code:
        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.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Rangers (03-11-2011)

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,171
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    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.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New Coder
    Join Date
    Oct 2010
    Location
    Denver
    Posts
    26
    Thanks
    8
    Thanked 0 Times in 0 Posts
    Would it look something like this?

    Code:
    <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
    Code:
    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

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,171
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    Looks right to me.

    But you don't have a SUBMIT button; you just have a button.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Rangers (03-10-2011)

  • #7
    New Coder
    Join Date
    Oct 2010
    Location
    Denver
    Posts
    26
    Thanks
    8
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    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?

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,171
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    I don't see why, since you are invoking nextQuestion.

    Can you put this up live someplace to look at?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    New Coder
    Join Date
    Oct 2010
    Location
    Denver
    Posts
    26
    Thanks
    8
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    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.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,171
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    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:
    Code:
    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

    Code:
    <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()" />
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Rangers (03-11-2011)

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,171
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    If you need the hidden fields to be numbered starting at 1, then change the JS from
    Code:
    form["q" + qNumber ].value = form.answer.value;
    to
    Code:
    form["q" + (qNumber + 1) ].value = form.answer.value;
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    New Coder
    Join Date
    Oct 2010
    Location
    Denver
    Posts
    26
    Thanks
    8
    Thanked 0 Times in 0 Posts
    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.

    Code:
    <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 | |
    +-------+--------------+------+-----+---------+----------------+

    Last edited by Rangers; 03-11-2011 at 12:20 AM.

  • #13
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,171
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    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:
    Code:
    <form ...>
    <input type="hidden" name="POSTBACK" value="YES" />
    ...
    And then my PHP code would do this:
    Code:
    <?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
    Code:
    <form action="processAnswsers.php" method="post">
    and then just put your DB INSERT code into "processAnswers.php" and *NOT* into the <form> page!
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Rangers (03-11-2011)

  • #14
    New Coder
    Join Date
    Oct 2010
    Location
    Denver
    Posts
    26
    Thanks
    8
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    So the easy answer to that is to do
    Code:
    <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!

  • #15
    New Coder
    Join Date
    Oct 2010
    Location
    Denver
    Posts
    26
    Thanks
    8
    Thanked 0 Times in 0 Posts

    PHP Sessions? Need to submit all data so it will show up on the same line in mysql db

    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



    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!


  •  
    Page 1 of 2 12 LastLast

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •