0

I'm making a hangman game. When the user clicks a letter, it gets appended to the url, like guess=G but in the event that I click the reset button (a submit button) the guess will still be in the URL, and the following function fires.

    function reset_game() {
        $_SESSION["word"] = generate_word("dictionary.txt");
        $_SESSION["word-progress"] = turn_to_underscores($_SESSION["word"]);
        $_SESSION["chances-left"] = 9;
        $_SESSION["guesses"] = array();
        $_SESSION["incorrect-guesses"] = array();

        header('Location: index.php');
    }

This is great, except that because of the GET request still being in the URL, it will submit it as a guess until I click the button one more time.

This is because further down in my code I check if there's a GET request and act on it if there is. Is there a way that I can make it clear the GET request on click of the reset button (sans JavaScript, more so with PHP) instead of having an if statement when it checks if the guess is right? The latter solution sounds... work-aroundy.

Doug Smith
  • 29,668
  • 57
  • 204
  • 388

2 Answers2

1

Give each submit button a different name attribute value, and key your processing over which name you find in $_GET. For example, if you have submit buttons with names of "guess" and "reset" then you can test isset($_GET['guess']) to see if the "guess" button was clicked, and isset($_GET['reset']) to see if the "reset" button was clicked.

For further reading on this approach, see this question and answer.

Alternatively, put the two buttons in different <form> elements, which will keep their respective <input> elements isolated from each other.

Community
  • 1
  • 1
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • For the first option, I was considering that (as stated in my question) but checking to see if there was a reset request whenever I check the guess seems unintuitive. If that's the only option I'm fine with it obviously. For the second option, they're anchor tags with get requests in the URL, not buttons, but they are in separate forms. – Doug Smith Feb 19 '13 at 16:14
0

Figured it out. Made sure my forms submitted with the attribute action="index.php" rather than simply action="", which kept the GET request in the URL.

Doug Smith
  • 29,668
  • 57
  • 204
  • 388