1

when i select any radio button on this form in index.php ,the condition for the value in radio button is not validated for the correct answer

index.php

<html>
<head>Aptitude Test</head>
<body>
<?php require_once 'config.php';?>
<?php $response=mysql_query("select * from questions");?>    
<form method='post' id='quiz_form' >
<?php while($result=mysql_fetch_array($response)){ ?>
<div id="question_<?php echo $result['id'];?>" class='questions'>
<h2 id="question_<?php echo $result['id'];?>">
<?php echo $result['id'].".".$result['question'];?>
</h2>
<div class='align'>
<input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>' >
<label id='answer1_<?php echo $result['id'];?>' for='answer1_<?php echo $result['id'];?>'><?php echo $result['answer1'];?></label>
<br/>
<input type="radio" value="2" id='radio2_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>' >
<label id='answer2_<?php echo $result['id'];?>' for='answer2_<?php echo $result['id'];?>'><?php echo $result['answer2'];?></label>
<br/>
<input type="radio" value="3" id='radio3_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>' >
<label id='answer3_<?php echo $result['id'];?>' for='answer3_<?php echo $result['id'];?>'><?php echo $result['answer3'];?></label>
<br/>
<input type="radio" value="4" id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>' >
<label id='answer4_<?php echo $result['id'];?>' for='answer4_<?php echo $result['id'];?>'><?php echo $result['answer4'];?></label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
</div>
<br/>
<input type="button" id='next<?php echo $result['id'];?>' value='Next!' name='question' class='butt'/>
</div>
<?php }?>
</form>
<div id='result'>
<img src='results.jpg' alt='Results'/>
<br/>
</div>

<div id="demo1" class="demo" style="text-align:center;font-size: 25px;">00:00:00</div>
<script src="jquery-1.9.1.min.js"></script>
<script src="watch.js"></script>
<script>
$(document).ready(function(){
$('#demo1').stopwatch().stopwatch('start');
var steps = $('form').find(".questions");
var count = steps.size();
steps.each(function(i){
    hider=i+2;
    if (i == 0) {   
        $("#question_" + hider).hide();
        createNextButton(i);
    }
    else if(count==i+1){
        var step=i + 1;
        //$("#next"+step).attr('type','submit');
        $("#next"+step).on('click',function(){

           submit();

        });
    }
    else{
        $("#question_" + hider).hide();
        createNextButton(i);
    }

});
function submit(){
     $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: $('form').serialize(),
                    success: function(msg) {
                      $("#quiz_form,#demo1").addClass("hide");
                      $('#result').show();
                      $('#result').append(msg);
                    }
     });

}
function createNextButton(i){
    var step = i + 1;
    var step1 = i + 2;
    $('#next'+step).on('click',function(){
        $("#question_" + step).hide();
        $("#question_" + step1).show();
    });
}
setTimeout(function() {
      submit();
}, 50000);
});
</body>
</html>

This is ajax.php which gets the selected radio button answer to check the answer is right or wrong, but the thing is the right answer condition if($_POST[$i] == $row['answer']) fails to check and does not increment the value $right_answer++;

ajax.php

 <?php require_once 'config.php';
 $query = "select id,question,answer from questions";
 $result=mysql_query($query) or die(mysql_error());
 $right_answer=0;
 $wrong_answer=0;
 $unanswered=0;
 $i=1;
 while($row=mysql_fetch_array($result))
{ 
    if($_POST[$i] == $row['answer'])
    {
        $right_answer++;
    }
    else if($_POST[$i]==5)
    {
        $unanswered++;
    }
    else
    {
        $wrong_answer++;
    }
    $i++;
 }
 echo "<div id='answer'>";
 echo " Right Answer  : <span class='highlight'>". $right_answer."</span><br>";

 echo " Wrong Answer  : <span class='highlight'>". $wrong_answer."</span><br>";

 echo " Unanswered Question  : <span class='highlight'>". $unanswered."</span><br>";
 echo "</div>";
?>

config.php file:

<?php
define('DB_HOST','localhost');
define('DB_NAME','Aptitude');
define('DB_USER','root');
define('DB_PASSWORD','');
$conn=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$conn) or die("Failed to connect to MySQL: " . mysql_error());


?>

Please help me to solve this problem. Thanks in advance.

Sparky
  • 98,165
  • 25
  • 199
  • 285
Amirtha Rajan
  • 605
  • 10
  • 19
  • Can i put the ajax.php code in index.php itself ? – Amirtha Rajan Dec 14 '13 at 15:41
  • Please do not use the [tag:jquery-validate] tag when your question has nothing to do with this plugin. Edited. Thanks. – Sparky Dec 14 '13 at 17:37
  • ok sorry i will change – Amirtha Rajan Dec 14 '13 at 17:51
  • @AmirthaRajan `Can i put the ajax.php code in index.php itself?` -- No, you can't do that. You have to have the server-side processing code in a separate PHP file. [See this answer](http://stackoverflow.com/questions/20572601/change-php-variable-with-ajax/20572741#20572741) – cssyphus Dec 15 '13 at 22:57
  • @AmirthaRajan Has this question been answered to your satisfaction? If so, please choose a correct answer to close the question. If there are additional parts to the question, it is better to close the first question (by selecting a correct answer) and then ask a new question for the next part. Your new question will appear at the top of the list, and will benefit from fresh exposure and more immediate assistance. – cssyphus Dec 16 '13 at 16:26

3 Answers3

1

This is not a full answer, but it will get you a long way down the road to a solution.

You were missing a few elements to your solution, but the most important omission was the javascript/jQuery.

jQuery is a javascript library that makes writing javascript MUCH shorter, simpler and more logical. jQuery can do almost anything that javascript can -- but to use it you must reference the jQuery library in the <head> tags, as I have done.

With jQuery you can trap each click of a NEXT button and figure out what question was clicked. Then, you can run an ajax procedure and get the correct answer for that question.

AJAX is a javascript/jQuery procedure that allows you to ask the server to look something up for you, and then send back an answer. You cannot use ajax without javascript, and it is tons simpler to use the $.ajax() methods from jQuery than to use the XMLHTTPRequest methods of pure javascript.

To re-create your situation, I created a database with 7 fields:

  • id - INT - the question number
  • question - VARCHAR - the question text
  • answer - VARCHAR - the correct answer
  • answer1 - VARCHAR - multiple-choice answer #1
  • answer2 - VARCHAR - multiple-choice answer #2
  • answer3 - VARCHAR - multiple-choice answer #3
  • answer4 - VARCHAR - multiple-choice answer #4

FILE 1:

<?php 
    include 'connect.php'; //login to your database
    $response=mysql_query("select * from questions");
?>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                var ques, user_ans;
                $('[id^=next]').click(function() {
                    ques = $(this).attr('id').split('t')[1];
                    user_ans = $(this).parent().find('input:radio:checked').attr('id');
                    user_ans = user_ans.split('_')[0];
                    user_ans = user_ans.split('o')[1];

                    $.ajax({
                        type:'POST',
                        url: 'ajaxCheck.php',
                        data:'ques=' +ques+ '&ans='+user_ans,
                        success: function(data){
                            alert(data);
                            ques = data.split('|')[0];
                            ans = data.split('|')[1];
                            $('#correct_'+ques).val(ans);
                        }
                    }); //END ajax
                }); //END next button.click
            }); //END document.ready
        </script>
    </head>
    <body>
        <form method='post' id='quiz_form' >
            <?php while($result=mysql_fetch_array($response)){ ?>
                <div id="question_<?php echo $result['id'];?>" class='questions'>
                    <h2 id="question_<?php echo $result['id'];?>">
                        <?php echo $result['id'].".".$result['question'];?>
                    </h2>
                    <div class='align'>
                        <input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name="radio<?php echo $result['id'];?>" >
                        <label id='answer1_<?php echo $result['id'];?>' for='answer1_<?php echo $result['id'];?>'><?php echo $result['answer1'];?></label>
                        <br/>
                        <input type="radio" value="2" id='radio2_<?php echo $result['id'];?>' name="radio<?php echo $result['id'];?>" >
                        <label id='answer2_<?php echo $result['id'];?>' for='answer2_<?php echo $result['id'];?>'><?php echo $result['answer2'];?></label>
                        <br/>
                        <input type="radio" value="3" id='radio3_<?php echo $result['id'];?>' name='radio<?php echo $result['id'];?>' >
                        <label id='answer3_<?php echo $result['id'];?>' for='answer3_<?php echo $result['id'];?>'><?php echo $result['answer3'];?></label>
                        <br/>
                        <input type="radio" value="4" id='radio4_<?php echo $result['id'];?>' name='radio<?php echo $result['id'];?>' >
                        <label id='answer4_<?php echo $result['id'];?>' for='answer4_<?php echo $result['id'];?>'><?php echo $result['answer4'];?></label>
                        <input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
                        <br/>
                        <input type="text" disabled="disabled" id="correct_<?php echo $result['id'];?>" />
                    </div>
                    <br/>
                    <input type="button" id='next<?php echo $result['id'];?>' value='Next!' name='question' class='butt'/>
                </div>
            <?php }?>
        </form>
    </body>
</html>

FILE 2: ajaxCheck.php

$ques = $_POST['ques'];
$ans = $_POST['ans'];

$query = "select id,answer,answer1,answer2,answer3,answer4 from questions WHERE id='$ques'";
$result=mysql_query($query) or die(mysql_error());

$r = mysql_fetch_assoc($result);

//You need to send back the ques# so jQuery knows which question block to update.
$out = $ques . '|' . $r['answer'];

echo $out;
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • i entered your code, all the questions are displaying with the next button on the same page thanks for ur reply – Amirtha Rajan Dec 14 '13 at 04:11
  • Please don't advocate the use of blind string concatenation in queries - your example is ridiculously open to SQL Injection. At minimum, reference that what you're doing is unsafe, and shouldn't be used as-is. Best would be recommending (and using an example of) a parameterized query. – Clockwork-Muse Dec 14 '13 at 04:31
  • what is sql injection ? – Amirtha Rajan Dec 14 '13 at 07:59
  • 1
    @AmirthaRajan [This is SQL injection](http://xkcd.com/327/). [See also](http://www.veracode.com/security/sql-injection) and [this](https://www.udemy.com/blog/sql-injection-tutorial/) – cssyphus Dec 15 '13 at 23:00
  • Just now i have earned +15 reputation so only now i could voteup before that i was unable to vote for your useful answer and Thanks For Info about SQL INJECTION @gibberish – Amirtha Rajan Dec 17 '13 at 01:53
0

Can you try this, added name as name='myradio[]'

HTML:

 <input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='myradio[]' >

PHP

<?php
   print_r($_POST[myradio]);

 ?>
Krish R
  • 22,583
  • 7
  • 50
  • 59
  • I tried changing the name,but its the same . it isn't checking whether that correct answer radio button is checked. Thanks for reply – Amirtha Rajan Dec 14 '13 at 04:27
0

since i don't know what was the condition being checked i just wrote a echo statement before the condition and then i came to know that it was checking the value of radio button and not its answer so what i did was i changed the correct answer field in the database to the correct answer's no

while($response=mysql_fetch_array($result))
{      
           echo $response['answer'];//this showed the answer
           echo $_POST["$i"];//this showed the radio button no of the answer clicked
          //so thats why the condition when wrong all the time and so i changed the answer filed to the right answer's radio button number and hence the condition went true
    if($response['answer']==$_POST["$i"])
    {
    $right_answer++;    
    }
    else if($_POST["$i"]==5)
    {   
        $unanswered++;
    }
    else
    {
        $wrong_answer++;
    }
    $i++;
}
Amirtha Rajan
  • 605
  • 10
  • 19