Skip to content
PHP Logo

In the context of the Hangman game issue described, how can JavaScript be utilized alongside PHP to improve user interaction and responsiveness?

The issue with the Hangman game described is the lack of user interaction and responsiveness due to the need for page refreshes after each guess. To improve this, JavaScript can be used to handle user input and update the game state dynamically without requiring a full page reload.

php
<?php
// PHP code for Hangman game with improved user interaction using JavaScript

$word = "hangman"; // Word to be guessed
$guessedWord = str_repeat("_", strlen($word)); // Initialize guessed word with underscores
$attempts = 6; // Number of attempts allowed

echo "<div id='word'>$guessedWord</div>";
echo "<div id='attempts'>$attempts</div>";

echo "<input type='text' id='guessInput'>";
echo "<button onclick='makeGuess()'>Guess</button>";

echo "<script>
    function makeGuess() {
        let guess = document.getElementById('guessInput').value;
        
        // Send the guess to a PHP script using AJAX
        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'handle_guess.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let response = xhr.responseText;
                // Update the guessed word and attempts remaining based on the response
                document.getElementById('word').innerHTML = response.guessedWord;
                document.getElementById('attempts').innerHTML = response.attempts;
            }
        };
        xhr.send('guess=' + guess);
    }
</script>";
?>