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>
Member Avatar for Rahul47

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);

Thank You

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.