1

I'm working on a fill-in-the-blank quiz (current state). In my index.php, I want to verify that the user input is the correct answer (as in, it matches what's in my MySQL server).

I can verify the answer is correct by <?php echo ... ?>-ing the answer, but this results in the answer being in the in the html file, which has the drawback of allowing cheating.

I gather from this answer, that I need to use something like $.post('file.php', {variable: variableToSend});, so I attempt to do that:

<script>
    function process_guess() {
        var input = [...snip...];

        [...snip...]

        var is_correct = $.post('process_answer.php', {guess: input});

        [...snip...]

        if(is_correct == 1) {
            [...snip...]
        }
        else {
            [...snip...]
        }
    }
</script>

The above Javascript function is called from a html form elsewhere in my index.php; I can used console.log to verify that the input variable above is the actual user input. However, judging from console.log, the way I'm using $.post is totally wrong, but I'm not sure what the correct syntax is.

In process_answer.php I have:

<?php
    if($_POST['guess'] == $problem_data["answer"]) echo "1";
    else echo "0"; 
?>

I'm not sure how to proceed from here.

Question: How do I determine if a HTML-form answer is correct (calling PHP via $.post), without revealing the answer?

1 Answers1

2

You're approach is good. The ajax call is a good way to do it.

In Javascript, according to the documentation, you just have to wait for a server response. But you have to notice that is asynchronous (so the code below, will probably be executed before your callback). I propose something like that.

$.post('process_answer.php', {guess: input})
  .done(function( data ) {
    // Execute your logic inside the request callback
    if(data) {
        [...snip...]
    }
    else {
        [...snip...]
    }
  }
);

And in your php, I suggest to exit the script or simply return a value

<?php
// return a json encoded boolean
header('Content-type: application/json');
echo json_encode($_POST['guess'] == $problem_data["answer"]);die;
?>

EDIT after Phil's comment :

Phil is right, I've updated my example.

Julien Bourdic
  • 1,398
  • 1
  • 12
  • 29
  • The PHP needs an `echo`, not a `return`. I would also add `header('Content-type: application/json')` and `json_encode()` the response – Phil Sep 09 '20 at 00:58
  • 1
    @Phil You're right, after a quick test, the return isn't sufficient. Bad habit from using frameworks :) – Julien Bourdic Sep 09 '20 at 01:11