0

Hello,

I have created a quiz system where I tried to create a condition which is just simple one if time is up then correct answer will be shown up and the button would be disabled but I am confused and unable to make some logic about I need you guys help I hope you will help me out

Thank You

<?php 
    function answer() {
        $answer = $_POST["ans"];

        if($answer == 'b') {
            echo "Correct answer!";
        } else {
            echo "Wrong answer!";
        }
    }
    $correct = 'b';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Quiz Sample</title>
<script type="text/javascript">
    function countdown(secs, elem, correct) {
        var answer  = correct;
        var element = document.getElementById(elem);
        element.innerHTML = "Please wait for "+secs+" Seconds"; 

        if(secs < 1) {
            clearTimeout(timer);
            element.innerHTML = "Timer completed Correct answer is"+answer+" !";                
        }

        secs--;
        var timer = setTimeout('countdown('+secs+', "'+elem+'")', 1000);
    }
</script>
</head>
    <body>
        <?php    
            if(isset($_POST["sub"])) {
                echo answer();
            }
        ?>
        <div id="status"></div>
        <form method="POST" action="quiz_test.php">
        <p>The question followed is below:</p>
            <input type="radio" value="a" name="ans" /> A
            <input type="radio" value="b" name="ans" /> B
            <input type="radio" value="c" name="ans" /> C
            <input type="radio" value="d" name="ans" /> D
        <input type="submit" name="sub" />
        </form>
        <script type="text/javascript">countdown(3, 'status', '<?php echo $correct; ?>');</script>
    </body>
</html>
2
Contributors
2
Replies
25
Views
2 Years
Discussion Span
Last Post by UK-1991
1

You are requesting quiz_test.php. If you have written any code for it please share it here. I am having difficulty comprehending what you are actually trying to do. My concern is why are you calling countdown() again and again ?

Well here are some modifications I did to your file which does the job but still it could be enchanced more efficiently if you just point out your intentions step by step.

Line 41: Changed action="quiz_test.php" to action="index.php"
Line 29:

var timer = setTimeout('countdown('+secs+', "'+elem+'")', 1000);

You forgot to send the answer parameter to countdown().
Modification:

      var timer = setTimeout('countdown('+secs+', "'+elem+'","'+answer+'")', 1000);

Edited by Rahul47: Added correct answer.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.