b p
b p

Reputation: 9

action after click on Radio button

I am using PHP MYSQL to generate a small multi page quiz. I am able to display the questions and the multiple choice answers as radio button choices(thanks to help from Stackoverflow). The problem I am running into is - is there a way to trigger an action as soon as a user clicks on a radio button? If the user has selected a wrong answer, I want to give immediate feedback and say the answer is wrong and why it is wrong. If the user has selected a correct answer, I want to display correct answer.

I have looked at $_GET,$_POST and $_REQUEST but all require the answers to be "Submit"ted for the process to begin in PHP. I want the action to begin (using PHP source code) as soon as the user clicks a radio button.

Note: I have looked at several questions here that seem to utilize jQuery for the above. Is it possible to do without jQuery or Javascript?

Thanks for your help.

Upvotes: 0

Views: 5626

Answers (5)

GreenRover
GreenRover

Reputation: 1516

Yes it is possible and to use jQuery is the best solution.

http://api.jquery.com/jQuery.ajax/

<?PHP
if (!empty($_GET['action']) && $_GET['action'] == 'ajax_check') {
  // I a final solution you should load here the answer of the question from database by name
  $answers = array(
    'foo' => 1,
    'baa' => 3,
  );    

  // Prepare and default answer in error case
  $return = array(
    'message' => 'Invalud choise',
  );

  if (isset($answers[$_GET['name']])) {
    // If question/answer was found in database, check if users chouse is correct
    if ($answers[$_GET['name']] == $_GET['value']) {
      $return['message'] = 'Correct answer'; 
    } else {
      $return['message'] = 'Wrong answer'; 
    }
  }

  // Return answer to java script
  header('Content-type: text/json');
  echo json_encode($return);
  die();
}
?>

Question 1
<input type="radio" name="foo" value="1" class="question_radio" />
<input type="radio" name="foo" value="2" class="question_radio" />
<input type="radio" name="foo" value="3" class="question_radio" />
<input type="radio" name="foo" value="4" class="question_radio" />
<br />

Question 2
<input type="radio" name="baa" value="1" class="question_radio" />
<input type="radio" name="baa" value="2" class="question_radio" />
<input type="radio" name="baa" value="3" class="question_radio" />
<input type="radio" name="baa" value="4" class="question_radio" />

<!-- Load jquery framework from google, dont need to host it by your self -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function () { 
    // When document was loadet succesfull

    $(".question_radio").click(function () {
      // Listen on all click events of all objects with class="question_radio"
      // It is also possible to listen and input[type=radio] but this can produce false possitives.

      // Start communication to PHP
      $.ajax({
        url: "test.php", // Name of PHP script
        type: "GET",
        dataType: "json",  // Enconding of return values ²see json_encode()
        data: { // Payload of request
          action: 'ajax_check', // Tel PHP what action we like to process
          name: $(this).attr('name'),
          value: $(this).val(), 
        }
      }).done(function(data) {
        // Procces the answer from PHP
        alert( data.message );
      });
    });
  });
</script>

Upvotes: 3

Priya
Priya

Reputation: 1554

Try this

$("input[type='radio'].your_radio_class").bind("change click", function(){
    //  stopping user from changing the answer further depends on ui specification
    //  disabling radio
    $("input[type='radio'].your_radio_class").each(function(){ 
       $(this).attr({"disabled":true,"readonly":"readoly"});
    });
    // else  show loading graphics
    $(this).parent().html("Loading answer...wait");
    //  make ajax call
    //  fetch answer
    //  display answer
});

Upvotes: 1

Peon
Peon

Reputation: 8020

This can be best accomplished with javascipt ( jQuery might be easier for you ).

1st: You set up a click event, that will trigger an action when a radiobutton is clicked:
http://api.jquery.com/click/

2nd: When the click is triggered, you set up an ajax call to a php file, that validates the input and returns the results:
http://api.jquery.com/jQuery.ajax/

The rest is up to you.

Upvotes: 0

Johny
Johny

Reputation: 175

If you want to validate the users choice before he actually hits the submit button ,you need to use the onchange property to fire up an ajax function (with parameters )for the radio button which you want to validate , the ajax will then get the response from the server aka the php code where you validate the user's choice and return the result.(if you do it right)

Upvotes: 0

UnholyRanger
UnholyRanger

Reputation: 1971

The thing you have to consider is the fact that PHP runs on the server side. With this said, you can ONLY do it with a request being sent to the server to handle. This is the 'submit' action or a JQuery/JavaScript/Ajax call which are run locally that make a request to the server and then updates the page. So to do it with PHP, you have to submit or use a local script to make a call.

Upvotes: 0

Related Questions